How to i get the values of particular field for Example: son, flower(Title) from
json = [{"pk": 1, "model": "book", "fields": {"title": "sum", "author": "son", "description": "dfg"}}, {"pk": 2, "model": "book", "fields": {"title": "Eradication", "author": "flower", "description": "nandhu"}}]
using ajax in ajax success part. Can anyone help me ?
With jQuery, you can just use the getJSON function as such:
$.getJSON('{% url your_json_view %}', function(data) {
for(var i=0; i<data.length; i++) {
if (data[i].fields.author == 'flower') {
alert('I got the book by flower');
}
}
});
Just to make sure, here's the python view that goes with it:
def your_json_view(request):
# ... build your data
return http.HttpResponse(simplejson.dumps(data))
The url should be defined nicely with a name too:
url(r'/your/json/view/', 'your_json_view', name='your_json_view')
Related
I am having a json object like the one below which I am reading from an xml file. I can see on the alert that the json obj is being displayed.
Now that I have the json object I am trying to bind against a Bootstrap datatable like in this example
How to load JSON data into Bootstrap table?
Whatever I tried the bootstrap table won't get populated. I think is because my json object contains the "book", which is the object name while the example from the link above has just a Json array. However I tried to do book.author and it still not working.
This is my plnk attempt, if anyone can have a look and tell what I am doing wrong would be great. https://plnkr.co/edit/h9islDjHyz6Sxkhl
{
"book": [
{
"author": "Gambardella, Matthew",
"title": "XML Developer's Guide",
"genre": "Computer",
"price": "44.95",
"publish_date": "2000-10-01",
"description": "An in-depth look at creating applications \n with XML.",
"id": "bk101"
},
{
"author": "Ralls, Kim",
"title": "Midnight Rain",
"genre": "Fantasy",
"price": "5.95",
"publish_date": "2000-12-16",
"description": "A former architect battles corporate zombies, \n an evil sorceress, and her own childhood to become queen \n of the world.",
"id": "bk102"
}
]
}
var $table = $('#table');
var mydata = "";
//read data from XML
$.get('hello.xml', function(xml) {
var json = $.xml2json(xml);
console.log(json);
// This part is for displaying the json result in this example
var jsonAsString = JSON.stringify(json, null, 2);
setJsonVal(jsonAsString);
});
//set mydata variablle with the json obj from XML
function setJsonVal(value){
mydata = value;
alert(value)
}
$(function () {
$('#table').bootstrapTable({
data: mydata
});
});
You need to use JSON.parse() to convert the value to json and then you can access the book by using .book.
function setJsonVal(value){
mydata = JSON.parse(value).book;
alert(value)
$('#table').bootstrapTable({
data: mydata
});
}
I have my html working with javascript, and the file manifest.json to be read.
Here is my json file's code:
{
"name": "Project",
"description": "A template project",
"icon": "img/icon.svg",
"version": "X.X.X.X",
"developer": {
"name": "Daniell Mesquita",
"url": "http://about.me/daniellmesquita"
},
"shop_id": "1",
"manifest_version": 1,
"default_language": "en"
}
I need read each object as text, parsing in javascript. Example:
<h1>+ name +</h1>
<h2>+ description +</h2>
<img src="+ icon +"/>
<p>+ version +</p>
Too, how can I read sub-objects of "developer" object?
EDIT: Validated json. Thanks to #ADreNaLiNe-DJ and Curious Concept's JSON Formater for helping validate.
You might do like the following. It will get your object key value pairs flattened even if you have nested objects in your data structure.
var data = {
"name": "Project",
"description": "A template project",
"icon": "img/icon.svg",
"version": "X.X.X.X",
"developer":
{
"name": "Daniell Mesquita",
"url": "http://about.me/daniellmesquita"
},
"shop_id": "1",
"manifest_version": "1",
"default_language": "en",
},
stack = [[],[]];
function getKeyValuePairs(obj,stack) {
Object.keys(obj).forEach( e => obj[e] instanceof Object ? getKeyValuePairs(obj[e], stack) : (stack[0].push(e), stack[1].push(obj[e])));
}
getKeyValuePairs(data, stack);
document.write("<pre>" + JSON.stringify(stack,null,2) + "</pre>");
If the json is in a String variable convert it to an object. Then you can access the single values:
var obj = JSON.parse(jsonString);
var name = obj.name;
var version = obj.version;
var developerName = obj.developer.name;
Well you can use
yourJsonVarName.developer.name
yourJsonVarName.developer.url
try this!
Added
If your external file is in your domain maybe you can use this to retrieve your data inside json file.
$.getJSON( "manifest.json", function( data ) {
var name = data.developer.name;
var url = data.developer.url;
});
I am using backbone's fetch method to retrieve a set of JSON from the server. Inside the fetch call, I have a success callback that correctly assigns attributes to a model for each object found.
var foo = assetCollection.fetch({
reset: true,
success: function(response){
var data = response.models[0].attributes.collection.items;
data.forEach(function(data){
assetCollection.add([
{src_href: data.data[0].value,
title: data.data[1].value
}
]);
});
console.log(assetCollection.models)
}
})
Right now I am working with a static set of JSON that has two objects. However, logging assetCollection.models returns three objects: the first is the initial server JSON response, while the next two are correctly parsed Backbone models.
How do I keep Backbone from adding the first object (the entire response from the server) to its set of models, and instead just add the two JSON objects that I am interested in?
The JSON object returned from the server is as follows:
{
"collection": {
"version": "1.0",
"items": [
{
"href": "http://localhost:8080/api/assets/d7070f64-9899-4eca-8ba8-4f35184e0853",
"data": [
{
"name": "src_href",
"prompt": "Src_href",
"value": "http://cdn.images.express.co.uk/img/dynamic/36/590x/robin-williams-night-at-the-museum-498385.jpg"
},
{
"name": "title",
"prompt": "Title",
"value": "Robin as Teddy Roosevelt"
}
]
},
{
"href": "http://localhost:8080/api/assets/d7070f64-9899-4eca-8ba8-4f35184e0853",
"data": [
{
"name": "src_href",
"prompt": "Src_href",
"value": "http://b.vimeocdn.com/ts/164/830/164830426_640.jpg"
},
{
"name": "title",
"prompt": "Title",
"value": "Mrs. Doubtfire"
}
]
}
]
}
}
You should modufy collection.
Probably you should change parse method:
yourCollection = Backbone.Collection.extend({
parse: function(data) {
return data.models[0].attributes.collection.items;
}
})
When you use fetch Backbone parse result and add all elements what you return in parse.
I'm having trouble finding a solution that will help me loop through a bunch of elements and putting the chosen values into a table. I've been able to withdraw some values but the method isn't dynamic.
Here is an example:
var Table = {
"credit": {
"link": "site link",
"logoUrl": "logo url",
"message": "message"
},
"groups": [
{
"labels": [
{
"name": "Western Conference",
"type": "conference"
},
{
"name": "Central Division",
"type": "division"
}
],
"standings": [
{
"stats": [
{
"name": "gp",
"value": 20
},
{
"name": "w",
"value": 17
},
{
"name": "l",
"value": 0
},
{
"name": "gf",
"value": 64
},
{
"name": "ga",
"value": 37
},
{
"name": "gd",
"value": 27
},
{
"name": "pts",
"value": 37
}
],
"team": {
"id": 12345,
"link": "team link",
"name": "team name",
"shortName": "team"
}
},
This is the structure of the elements. So far I've used this:
document.getElementById("sGamesPlayed").innerHTML=Table.groups[0].standings[0].stats[0].value;
to withdraw values. However there are more teams, stats and divisions so I would need some kind of loop to go through the elements and put the into a dynamic table.
I would consider you to look at http://underscorejs.org/.
it provides a bunch of utility functions that could help you,
for example, _.each() helps you loop through JSON properties.
for the sample objects you've given (after completing the missing brackets at the end),
_.each(Table.groups[0].standings[0].stats, function(stats){
console.log(stats['name']+","+stats['value'])
})
gives me:
gp,20
w,17
l,0
gf,64
ga,37
gd,27
pts,37
how it works is that you provide the object you want as the first argument and the function that you give as the second argument will be called with each element of the first argument (Assuming it is a list).
I would also urge you to look at underscore templating that you can use to render your table where i put the console.log :
http://net.tutsplus.com/tutorials/javascript-ajax/getting-cozy-with-underscore-js/
http://scriptble.com/2011/01/28/underscore-js-templates/
I guess your question is about filtering the values of the array standings. In order to do that you can use the jQuery grep function (if you want to use jQuery).
For example you can write:
var arr = $.grep(Table.groups[0].standings[0].stats, function(d){return d.value>25})
Which will give
arr = [{"name": "gf","value": 64}, {"name": "ga", "value": 37},{"name": "gd", "value": 27},{"name": "pts", "value": 37}]
If this is not what you meant, can you please create a jsFiddle with a sample of what you want?
Depending on what you want to do with the results, you can go over the object using a scheme like:
var groups, standings, stats, value;
groups = Table.groups;
// Do stuff with groups
for (var i=0, iLen=groups.length; i<iLen; i++) {
standings = groups[i].standings;
// Do stuff with standings
for (var j=0, jLen=standings.length; j<jLen; j++) {
stats = standings[j];
// Do stuff with stats
for (var k=0, kLen=stats.length; k<kLen; k++) {
value = stats[k].value;
// Do stuff with value
}
}
}
Of course I have no idea what the data is for, what the overall structure is or how you want to present it. But if you have deeply nested data, all you can do is dig into it. You might be able to write a recursive function, but it might also become very difficult to maintain if the data structure is complex.
I'm have a little trouble with some jQuery I have been trying to put together today.
Basically what I am trying to achieve is to dynamically have prices inserted into a price button on my page by reading from a JSON feed.
The idea is that there is an empty span that will contain the price. I have given all of the price spans the class .getPriceNew. Each span also has an id which is equal to the SKU number for the item like this <span class="getPriceNew" id="123456"></span>.
The mechanic is that for each span that has the class .getPriceNew the JSON will be queried for the information with the SKU id used as part of the query string.
Here is an example of the code i have tried
jQuery
$(".getPriceNew").each(function() {
var sku = $(this).attr("id");
var priceNew = $.getJSON('/api/MyApi.svc/GetProductBySku/'+sku , function(data) {
return(data.Variants[0].Price);
});
$(this).html("€"+priceNew);
})
HTML
<span class="getPriceNew" id="123456"></span>
<span class="getPriceNew" id="789123"></span>
<span class="getPriceNew" id="456789"></span>
<span class="getPriceNew" id="654321"></span>
JSON Example
This is what a single item from the JSON feed would look like - I have filtered it a little
/api/MyApi.svc/GetProductBySku/123456
Updated with valid JSON
{
"Age": {
"Description": "Age 18+",
"Thumbnail": "http://someurl.com/productImages/assets/img//icon18.gif"
},
"Barcode": {
"Barcode": "5026555408684"
},
"Description": "HTML",
"Id": 12214,
"Packshots": [
"http://someurl.com/productImages/914383/1min.jpg",
"http://someurl.com/productImages/914383/2med.jpg",
"http://someurl.com/productImages/914383/3max.jpg"
],
"Pegis": [],
"Platform": {
"Button": "Format",
"ID": 0
},
"Publisher": {
"Description": null
},
"Release": "/Date(1364252400000+0100)/",
"Screenshots": [],
"Title": "Product Title",
"Variants": [
{
"Id": 22488,
"MaxOrderQuantity": 3,
"Presellable": true,
"Price": 49.97,
"Sku": 914383,
"Type": {
"Description": "Pre-Order"
}
}
],
"Vendor": {
"Description": "Take Two Interactive Software"
},
"VideoHTML": "HTML",
"status": {
"Response": "product found",
"Success": true
}
}
I would love some help on this as I am really scratching my newbie head at this stage. I have managed to have console.log output the prices to the log but when I try and insert them back into the spans all I get is [object] [Object].
You are doing
$(".getPriceNew").each(function() {
var sku = $(this).attr("id");
var priceNew = $.getJSON('/api/MyApi.svc/GetProductBySku/'+sku , function(data) {
return(data.Variants[0].Price);
});
$(this).html("€"+priceNew);
})
getJSON returns a jqXHR object, which is not what you need. Try this:
$(".getPriceNew").each(function() {
var sku = $(this).attr("id");
// Save a refference to this span.
var thisSpan = $(this);
$.getJSON('/api/MyApi.svc/GetProductBySku/'+sku , function(data) {
// Request complete, NOW we can use the data we got!
thisSpan.html("€"+data.Variants[0].Price);
});
})
The callback is where you want to use the data you get from your AJAX calls. All AJAX methods ($.ajax, $.get, $.post, $.getJSON, etc) will return a jqXHR object.
I think your javascript code is correct but your Json output has two errors:
1: "Description":"Some HTML Description here, <- you forgot the closing quote
2: "ID":0}, <- delete the closing brace
So your Json will result like this:
{
"Age": {
"Description": "Age 18+",
"Thumbnail": "http://url.com/image.gif"
},
"Barcode": {
"Barcode": "4876416541647"
},
"Description": "Some HTML Description here",
"Id": 12214,
"Packshots": [
"http: //url.com/productImages/914383/1min.jpg",
"http: //http: //url.com/2med.jpg",
"http: //http: //url.com/3max.jpg"
],
"ID": 0,
"Publisher": {
"Description": null
},
"Release": "/Date(1364252400000+0100)/",
"Screenshots": [],
"Title": "Titleoftheproduct",
"Variants": [
{
"Id": 22488,
"MaxOrderQuantity": 3,
"Presellable": true,
"Price": 49.97,
"Sku": 914383,
"Type": {
"Description": "Pre-Order"
}
}
],
"Vendor": {
"Description": "Vendorname"
},
"VideoHTML": "<iframewidth="725"height="408"src="http: //www.youtube.com/embed/videoseries?list=PLofwA47XDv2_KnfUY52_8mlWg0iUEv8ci"frameborder="0"allowfullscreen></iframe>",
"status": {
"Response": "productfound",
"Success": true
} }
now your code
data.Variants[0].Price
will return 49.97
to validate Json you can paste it into http://jsonlint.com/ i think is very useful
Hope this helps