I'm getting a JSON response from the server and i have to loop through the array in javascript and get the values. But I cant seem to loop throught it.
The JSON response of the array looks like this:
{
"1": "Schools",
"20": "Profiles",
"31": "Statistics",
"44": "Messages",
"50": "Contacts"
}
I just want to loop through it to get the ID and Name and populate some values on the page.
I have tried:
$.each(response, function(key, value) {
alert(key + ' ' + value);
});
// and
for (var key in response) {
alert(key + ' ' + response[key]);
}
But neither give the right values.
Thanks in advance for any help.
Reply:
Hi,
The response I'm getting with the second loop is:
0 {
1 "
2 1
3 "
4 :
5 "
6 S
etc etc
So that means its going through the whole response as a string and spliting it as key/value.
Thanks
Your problem is that you are not parsing the JSON string. Therefore, your foreach is going through the characters in the JSON string.
// If you are using jQuery.ajax, you can just set dataType to 'json'
// and the following line will be done for you
var obj = jQuery.parseJSON( response );
// Now the two will work
$.each(obj, function(key, value) {
alert(key + ' ' + value);
});
for (var key in obj) {
alert(key + ' ' + response[key]);
}
var response = {"1":"Schools","20":"Profiles","31":"Statistics","44":"Messages","50":"Contacts"};
for (var i in response) {
console.log(i + ' ' + response[i]);
}
Works just fine, how are you getting your response var?
You don't need to do like that, dealing with string is a boring job. You can make a object through the response.
1:json = eval(xmlHttp.responseText);
but this is unsafe in some degree.
json = JSON.parse(xmlHttp.responseText, function(key,value){// can do some other stuff here.});
then you can operate the variable as a normal object like this obj.a or obj["a"].
May this will help you.
http://jsfiddle.net/sG5sF/
jQuery.each works fine. So is for-each loop
http://jsfiddle.net/TfjrS/
Both of them work as they should. You might have errors in other parts of your code. Is the response variable set correctly to the JSON object given in your question? Are you checking the response statusCode? it should be 200 for a successful response?
Consider looking at How can I parse a JavaScript object with jQuery for a possible answer.
You can use for-in construct in pure Javascript. Of course, you need to be careful that you're only looking at the object's own properties (libraries like Prototype tend to pollute):
for(var key in response) {
if(response.hasOwnProperty(key)) {
...
}
}
EDIT
Are you using jQuery.ajax? What's the dataType value? It should be json. This might be why your response is being interpreted as a string. Also, when you console.log response, does it show up as a string or an object?
Related
i have a little problem, i am a beginner in programming. I want to work with the Erast API, a Formula 1 API. I want to get all the drivers who won single races, the request is the following:
http://ergast.com/api/f1/current/results/1.json
Structure of the return values:
Problem is, that i dont know how to parse the JSON into a JS Array, I thought something like that:
var names = [];
var index = 0;
$.getJSON("http://ergast.com/api/f1/current/results/1.json", function(data, status) {
$.each(data.MRData.RaceTable.Races, function(name, value) {
//names.push(value.Results[0].Driver.givenName + " " + value.Results[0].Driver.familyName));
obj = $.parseJSON(value);
names.push(obj.Results[0].Driver.givenName);
//console.log(value.Results[0].Driver.givenName+ " " + value.Results[0].Driver.familyName);
});
});
If anyone knows the answer, would appreciate hearing from you
There is no need to parse JSON in the loop: jQuery has already decoded the JSON when it got the response in its implementation of $.getJSON.
So you can do this (also using map()):
$.getJSON("http://ergast.com/api/f1/current/results/1.json", function(data, status) {
var names = data.MRData.RaceTable.Races.map(function(value) {
return value.Results[0].Driver.givenName;
});
console.log(names);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I am getting the data from an API using JavaScript.
The statement console.log(json[0]) gives the result:
{"id":"1","username":"ghost","points":"5","kills":"18","xp":"10","diamonds":"0","level":"1","missionscomplete":"1"}
Now I am trying to print the individual elements of this dictionary. How do I do this ? My code is below:
function loadLeaderboard(){
$.get("http://localhost:8888/l4/public/api/v1/getLeaderboard",function(data){
var json = $.parseJSON(data);
console.log(json[0]);
$.each(json[i], function(key, data) {
console.log(key + ' -> ' + data);
});
});
}
EDIT:
The value of data as returned by the API is
["{\"id\":\"1\",\"username\":\"ghost\",\"points\":\"5\",\"kills\":\"18\",\"xp\":\"10\",\"diamonds\":\"0\",\"level\":\"1\",\"missionscomplete\":\"1\"}","{\"id\":\"2\",\"username\":\"seconduser\",\"points\":\"0\",\"kills\":\"3\",\"xp\":\"0\",\"diamonds\":\"0\",\"level\":\"0\",\"missionscomplete\":\"0\"}","{\"id\":\"3\",\"username\":\"goat\",\"points\":\"12\",\"kills\":\"13\",\"xp\":\"14\",\"diamonds\":\"10\",\"level\":\"10\",\"missionscomplete\":\"4\"}"]
The value in json after the operation var json = $.parseJSON(data); is
["{"id":"1","username":"ghost","points":"5","kills":…diamonds":"0","level":"1","missionscomplete":"1"}", "{"id":"2","username":"seconduser","points":"0","ki…diamonds":"0","level":"0","missionscomplete":"0"}", "{"id":"3","username":"goat","points":"12","kills":…amonds":"10","level":"10","missionscomplete":"4"}"]
You can just use stringify method of JSON-
console.log(JSON.stringify(json[0]));
Update
Your JSON data is a mess. It's not in the format you want. It should be an array of objects, but instead it is an array of strings, where each of those strings is the JSON representation of one of your user objects.
You could decode this in your JavaScript code, but you shouldn't have to. The JSON API should be fixed to generate a reasonable JSON object.
I don't know what language your server code is in, but it must be doing something like this pseudocode:
array = []
for each userObject in leaderBoard:
userJson = toJSON( userObject )
array.push( userJson )
jsonOutput = toJSON( array )
Instead, the code should look more like this:
array = []
for each userObject in leaderBoard:
array.push( userObject )
jsonOutput = toJSON( array )
In other words, the way to generate the JSON you want in most languages is to create an object or array with the structure you need, and then call the language's toJSON function (or whatever function you use) on that object or array. Let it generate all of the JSON in one fell swoop. Don't generate JSON for each individual element of your array and then generate JSON again for the entire array as a whole. That gives you an array of strings where you want an array of objects.
Original answer
What you're asking for is not what you really want to do.
Your JSON response returns an array of user objects, correct? That's why json[0] is a single object.
You probably want to loop over that array, but you don't loop over the individual objects in the array. You simply reference their properties by name.
Also, instead of using $.get() and $.parseJSON(), you can use $.getJSON() which parses it for you.
And one other tip: don't put the hostname and port in your URL. Use a relative URL instead, and then you can use the same URL in both development and production.
So for test purposes, let's say you want to log the id, username, and points for each user in your leaderboard JSON array. You could do it like this:
function loadLeaderboard() {
var url = '/l4/public/api/v1/getLeaderboard';
$.getJSON( url, function( leaders ) {
// leaders is an array of user objects, so loop over it
$.each( leaders, function( i, user ) {
// get the properties directly for the current user
console.log( user.id, user.username, user.points );
});
});
}
json[0] is an object, so you want to loop over the keys:
var o = json[0];
for (var key in o) {
if (o.hasOwnProperty(key)) {
console.log(key, o[key]);
}
}
Working fiddle: http://jsfiddle.net/UTyDa/
jQuery.each() is probably the easiest way, check this out: http://api.jquery.com/jQuery.each/
eg
$.each(json[0], function(key, data) {
console.log(key + ' -> ' + data);
});
EDIT:
What's the result of the following?
function loadLeaderboard(){
$.get("http://localhost:8888/l4/public/api/v1/getLeaderboard",function(data){
var json = $.parseJSON(data);
console.log(json[0]);
for(var i = 0; i < json.length; i++) {
$.each(json[i], function(key, data) {
console.log(key + ' -> ' + data);
});
}
});
}
EDIT 2: 'data' returned as array.
function loadLeaderboard(){
$.get("http://localhost:8888/l4/public/api/v1/getLeaderboard", function(data){
for(var i = 0; i < data.length; i++) {
var json = $.parseJSON(data[i]);
console.log('Data for index: ' + i);
$.each(json, function(key, val) {
console.log(key + ' -> ' + val);
});
}
});
}
I need help understanding the best way to manipulate a JavaScript data structure (if you call it that?). I come from a Perl background and am trying to iterate through a JavaScript data structure to update a div (or table) on the fly. Currently I'm just making the data a variable (data) to get going. once I have that sorted then I will use jquery's ajax methods to get the data as a json object on the fly. It's my understanding that the data structure I'm currently generating is the same thing I would get if it were json?? if not then I guess thats another question..
I have searched many times for such a tutorial but they are all close but haven't found one that meets my needs...
I would like to in the future be able to re-order the array and repopulate the #data_table div so part of my question is: is this even the best way to represent the data? Then I want to update just one part of the array like a companies phone number or add a person then redraw the div from this updated array...
The end result to the user could look like:
Company: 99 Beans, Auckland, Ph: 360499
People:
Matt, 6471
Christiaan, 6472
Michelle, 6473
Judy, 6474
Company: ....
* Next company and so forth..
My code so far is like this (except I have 500+ entries in the data array and only 2 here):
I have taken some of this code from another question I found here and tried to make it work for my type of structure..
<script>
$(document).ready(function() {
var r = new Array();
var data= [
{
"id":"6477",
"c":"99 Beans",
"ci":"Auckland",
"p":"09 360499",
"co":[
{"id":"6471","c":" NZ", "n":"Matt" },
{"id":"6472","c":" NZ", "n":"Chrstiaan" },
{"id":"6473","c":" NZ", "n":"Michelle" },
{"id":"6474","c":" NZ", "n":"Judy " },
{"id":"6475","c":" NZ", "n":"Kate " },
{"id":"6476","c":" NZ", "n":"Unknown Person" }
]
},
{"id":"7145", "c":"A1 Ltd", "ci":"Te Puke ","p":"06 870090",
"co":[{"id":"7145","c":" NZ", "n":"Alan" }
]
},
];
// this alert used to work, when I had the data as an array of arrays so there must be a problem with how I'm referencing it or my data structure is wrong??
alert (data.length + " companies" );//+ data[455].co[0].n);
var j = -1;
for (var key=0, size=data.length; key<size; key++) {
// first div
r[++j] ='<div>';
r[++j] = data[key].id;
r[++j] = ' - ';
r[++j] = data[key].c;
r[++j] = ' - ';
r[++j] = data[key].p;
r[++j] = '<br />';
//inner div
var k = -1 ;
for (var key1=0, size1=data[key].d.length; key1<size1; key1++) {
r[++j] ='<div>';
r[++j] = data[key].d.[key1].n + ' - ' + data[key].d.[key1].c + ' - ';
r[++j] = '</div>';
}
r[++j] = '</div>';
}
$('#data_table').html(r.join(''));
});
</script>
<div id="data_table"></div>
JSON's representation in Javascript is a javascript object.
var json = {
my_property: 2,
another_property: 'string!'
}
You can then fetch properties with json.my_property or json['my_property'] (which is nice if you don't know what exactly you are fetching, you can do var something = 'something-the-user-selected'; json[something]).
So, with jQuery, you would so something like this:
var json = {}; // get this from the server using $.AJAX() or $.getJSON()
$("#my_table").append("<tr><td>" + json.my_property + "</tr></td");
Or, if you got an array of, say, tweets, you should iterate over them, maybe with underscore's each, jQuery's each or plain old for (var i = 0; i < json.tweets.length; i++).
The data structure you are referring to is JSON.
With jQuery you can easily iterate your data structure with .each() and treat the returned value as an object with the attributes defined.
Here is a sample making the an Ajax call that will build your JSON object and iterating:
$.ajax({
type: "POST",
url: "MySite/MyResource",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if(data.d.length > 0){
$(data.d).each(function(){$('#mytable').append("<tr><td>Company: " + this.c + "</td></tr>");});
}
},
error: function (xhr, status, error) {
// do something appropriate
}
});
If you are looking to iterate farther then you can continue to call .each()
If data is your JSON value, this will format your specified string. (You'll have to JSONify your string to create it as the actual JSON object)
data.each(function(){
$('#mydiv').append('Company: ' + this.c + ', ' + this.ci + ', Ph: ' + this.p + ' People: ');
this.co.each(function(){$('#mydiv').append(this.n + ', ' + this.id);});
});
For the "rendering an JSON object to HTML", you may want to have a look at jQuery.template() which allows to render pieces of HTML with a template syntax. I have never used it so I do not know how well it can perform with very big lists... (also note that it is still in beta)
UPDATE
Here is a working example (it might not be optimal or anything) but you should see the general idea ;)
http://jsfiddle.net/tsimbalar/A9uYP/
UPDATE 2 for sake of completeness and traceability
There was a syntax error in the original code which prevented the alert() from executing (and all following code).
See comment :
Your code is not working because of a syntax error in
data[key].d.[key1].n., which is invalid syntax. (it should be data[key].d[key1].n, I suppose. Use the Firebug extension ofr Firefox to detect this kind of issues that would otherwise go unnoticed.
After fixing this typo, it is easy to iterate over the contents of the object using jQuery.each() as mentioned by catalpa in another answer. You can then build HTML elements (i.e. $("<div/>")) and append them to existing items of the page with append() . (see the fiddle about that part)
handlebars js templating is far better than jquery template and can be used for rendering complex json objects in html
I have a JSON response. The json post is: SubmitPerformedDeed. And i get this back:
{"error":false,"shareurl":"http://groenedaad-dev.lostboys.nl/?isnew=1&pid=155#pid=155","title":"Eigenhandig m’n kantoor een stukje duurzamer gemaakt. Check m’n Groene Daad voor vandaag!","pid":155,"firstname":"sdf","deedpoints":2,"deednumber":20,"deedtitle":"deed 20","company":"asdfsdf","office":"ass","alias":"sdfsxx","thumbnail":"/Uploads/Deeds/155/thumbnail.jpg"}
But how can i put that Json value's response in jquery. How can i put that in a array or ?
Use .parseJSON() and .each():
var parsedData = $.parseJSON(str);
$.each(parsedData, function(key, value) {
console.log(key + ': ' + value);
});
You should actually be able to just use .each() for this, as it's a "generic iterator function":
$.each(str, function(key, value) {
console.log(key + ': ' + value);
});
Someone please correct me if I'm wrong.
There is javascript out there that will take a JSON response and put it back in to a javascript object:
var myObj = JSON.parse(result);
You can use jQuery.parseJSON(response.responseText) in your success callback
you can use
$.each({your returned json},funciton(key,value){
});
here each function can iterate over each json element. so in loop's first iteration key represent "error" and value represent the "false" and so on. now you can store/use this method in accordance with your need.
I have this kind of json string:
{"total":"3","data":[{"id":"4242","title":"Yeah Lets Go!","created":"1274700584","created_formated":"2010-07-24 13:19:24","path":"http:\/\/domain.com\/yeah"}{"id":"4242","title":"Yeah Lets Go!222","created":"1274700584","created_formated":"2010-07-24 13:19:24","path":"http:\/\/domain.com\/yeah222"}{"id":"4242","title":"Yeah Lets Go!333","created":"1274700584","created_formated":"2010-07-24 13:19:24","path":"http:\/\/domain.com\/yeah333"}]}
I would need to parse it to javascript object i believe? And then into html like:
Yeah Lets Go!
<p class="date">Created: 2010-07-24 13:19:24"</p>
but I have no clue how to parse it and so on.
I get that string from this:
$('a.link').click(function() {
var item_id = $(this).attr("href").split('#')[1];
$.get(base_url+'/ajax/get_itema/'+item_id+'/0/3/true', null, function(data, status, xhr) {
$('#contentCell').html(data);
});
Use the JSON.parse function to convert a JSON string into a JS object. Most modern browsers include JSON.parse, but it is also included in json2.js if you need a fallback for older browsers.
Having a div with id result to get the html, something like:
$.getJSON(base_url+'/ajax/get_itema/'+item_id+'/0/3/true', function(data) {
$("#result").empty();
$.each(data.data, function(i, d) {
$("#result").append("<a href='" + d.path + "'>" + d.title + "</a>" +
"<p class='date'>Created: " + d.created_formated + "</p>");
}
});
Since you're using jQuery, take a look at .getJSON()
The way you use .getJSON() is:
jQuery.getJSON( url, [ data ], [ callback(data, textStatus) ] )
url is of course the url you're getting the data from. [ data ] is the stuff you send to the server. [ callback(data, textStatus) ] is a function that handles the data coming back from the server. You can generally leave out the second argument textStatus. The data coming back is understood to be JSON. .getJSON() is shorthand for a .ajax() call that specifies JSON data.
So in your case this would be something like (note that I changed the JSON coming back from the server to response... it's a less confusing nomenclature in your case than using data, since you have a data property in your JSON):
$.getJSON(base_url+'/ajax/get_itema/'+item_id+'/0/3/true', function(response) {
...
});
So, to recover things from response we simply access them using dot and square bracket notation. To get the first set of data:
response.data[0].title \\ <== "Yeah Lets Go!"
response.data[0].path \\ <== "http://domain.com/yeah"
The above looks in response which is our JSON object. Then it looks at the first data elment (there are 3) and pick the title in the first line and the path in the second.
Since you're using jQuery you can use .each() to iterate over your 3 data. Like this:
$.each(response.data, function(index, value) {
$("body").append('' + value.title + '');
$("body").append('<p class="date">Created: ' + value.created_formated +
'</p><br />');
});
jsFiddle example
.each() sanely loops over a collection of items. The first argument of .each(), is the object you want to loop over. This is response.data not merely response. This is because we want to look at response.data[0], response.data[1], and response.data[2]. The second argument of .each() is the callback function, or what we want to do with each of the items we are iterating over. Within the callback function, the first argument is automatically the index of the item (0, 1, or 2 in your case). The second argument is the value of the item. In your case this is a separate object: response.data[0], response.data[1], and response.data[2] respectively. We can use dot notation to retrieve the things we want directly from these objects. In the above example we access .path. .title and .created_formated from each of the values.
This make your entire function:
$.getJSON(base_url+'/ajax/get_itema/'+item_id+'/0/3/true', function(response) {
$.each(response.data, function(index, value) {
$("body").append('' + value.title + '');
$("body").append('<p class="date">Created: ' + value.created_formated +
'</p><br />');
});
});
Of course you probably want to append the response to (a) specific element/s.
Here's some good info on using .getJSON() to access multidimensional JSON data from another SO question.
Here's some general info about JSON in Javascript.
Note:
You need commas between your curly braces!
You have:
...p:\/\/domain.com\/yeah"}{"id":"4242","title"...
You need:
...p:\/\/domain.com\/yeah"}, {"id":"4242","title"...
I don't found in any answers that the data which you posted are NOT valid JSON string. Probably it is your main problem and the reason why $.get can not convert the server response to object. The objects inside the data array must be separated with commas. So the data must looks like
{
"total": "3",
"data": [
{
"id": "4242",
"title": "Yeah Lets Go!",
"created": "1274700584",
"created_formated": "2010-07-24 13:19:24",
"path": "http:\/\/domain.com\/yeah"
},
{
"id": "4242",
"title": "Yeah Lets Go!222",
"created": "1274700584",
"created_formated": "2010-07-24 13:19:24",
"path": "http:\/\/domain.com\/yeah222"
},
{
"id": "4242",
"title": "Yeah Lets Go!333",
"created": "1274700584",
"created_formated": "2010-07-24 13:19:24",
"path": "http:\/\/domain.com\/yeah333"
}
]
}
I recommend you allays verify JSON strings in http://www.jsonlint.com/.
Try a templating engine that convert the JSON to HTML on the browser.
You can have a look at pure.js, it is very fast, and keep the HTML totally clean of any Javascript templating logic.
We use it to generate all the HTML from JSON data in our web app.(Yep... I'm a main contributor to the lib)
If you are more familiar with the <%...%> or ${...} kind of templates, there are plenty of them and for any taste if you search on the web for javascript template.
using data from Oleg answer
var json = {} // your json data reformated by Oleg
for (var i = 0; i < json.data.length; i++) {
document.write('' + json.data[i].title + '');
document.write('<br>');
document.write('<p class="date">Created: ' + json.data[i].created_formated +'</p>');
document.write('<br>');
}
remember that the "data" is an array of object