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);
});
}
});
}
Related
I know there are 1 million and 1 questions on this, but I cannot seem to find an answer.
I am receiving data via PHP as such
echo json_encode($result);
From a typical MYSQL query.
I get the result back like this in the console.
[{"id" : "1", "name" : "bob"}]
I am trying to use $.each to iterate through this so I can process my results but I only get errors, undefineds or 0[object Object].. things like that.
My goal is to append each value to a input box (retrieving data from a table to put into an edit box).
$.post('getstuff.php', { id : id } function(data){
$.each(data), function(k,v){
$('input[name= k ]').val(v);
});
});
As you can see i was hoping it was as simple as a key=>value pair but apparantly not. I have tried parsing, stringifiying.. really I am lost at this point. I also cannot tell $.post that I am using JSON because I am using a more arbitrary function, but am just posting that as my example.
Edit
var retrievedData = JSON.parse(data);
$.each(retrievedData, function(k,v){
for (var property in retrievedData) {
if (retrievedData.hasOwnProperty(property)) {
console.log(k);
console.log(v);
console.log(property);
//$('input[name= k ]').val(v);
}
}
});
In your second code sample, retrievedData is an array, which you iterate using jQuery $each...
$.each(retrievedData, function(k, v) {
OK so far. But then you try to iterate retrievedData again like an object, which it isn't. This is why you are getting undefined messages in the console
for (var property in retrievedData) {
if (retrievedData.hasOwnProperty(property)) {
console.log(k);
console.log(v);
console.log(property);
//$('input[name= k ]').val(v);
}
}
On the inner loop you should be iterating v not retrievedData. On each pass of $each v will be an object.Try this:
$.each(retrievedData, function(k,v){
for (var key in v) {
if (v.hasOwnProperty(key)) {
console.log("key: " + key);
console.log("value: " + v[key]);
}
}
});
You should do some type checking that v is an object first and catch any errors.
Use either :
$.ajax({
'dataType' : 'json'
});
Or
$.getJSON
Or if you want to use $.post, just do in your success function :
var good_data = JSON.parse(data);
$.each(good_data, function(k,v) {
$('input[name= k ]').val(v);
});
Answering your question based on your comments on other answer.
My assumption is you are getting data as JSON,if not you need to parse it,for that you can use JSON.parse(string).
Here I'm using Underscore.js
var data=[{"id" : "1", "name" : "bob"}]
$(data).each(function(ind,obj){
var keys=_.keys(obj);
$(keys).each(function(i,ke){
console.log(ke)
console.log(obj[ke]);
})
});
Here is JSFiddle of working code
First you need to define you're expecting JSON in your POST request - http://api.jquery.com/jQuery.post/
Then you need to iterate through the response.
$.post('getstuff.php', { id : id } function(data){
//Assuming you get your response as [{"id" : "1", "name" : "bob"}], this is an array
//you need to iterate through it and get the object and then access the attributes in there
$.each(data), function(item){
$('input[name=' + item.name + ']').val(item.id);
});
}, 'json');
EDIT
If you want to iterate over the properties of the objects returned, you need to put another loop inside the $.each
for (var property in item) {
if (object.hasOwnProperty(property)) {
// do stuff
}
}
More about it here - Iterate through object properties
EDIT 2
To address the solution you've posted. You've used the wrong variable names. Here's a working fiddle - http://jsfiddle.net/EYsA5/
var $log = $('#log');
var data = '[{"id" : "1", "name" : "bob"}]'; //because we're parsing it in the next step
var retrievedData = JSON.parse(data);
for (var parentProp in retrievedData) { //this gets us each object in the array passed to us
if (retrievedData.hasOwnProperty(parentProp)) {
var item = retrievedData[parentProp];
for (var property in item) { //this gives us each property in each object
if (item.hasOwnProperty(property)) {
console.log(item[property]);
$log.prepend("<br>");
$log.prepend("Property name is - " + property);
$log.prepend("<br>");
$log.prepend("Value of property is - " + item[property]);
//do stuff
}
}
}
};
I have an array of objects that should be looking like this...
[{"Name":"blah","Description":"blah"},{"Name":"blah2","Description":"blah2"}]
Using Javascript/jQuery, how can I get the key/value pairs? I've tried many different ways but to no avail. When I try to get the length, it always returns the character count and iterates through each character and not the actual count of objects? When I run this, it returns an alert for [object Object], [object Object] spelled out by each character....
function DisplayItems(data) {
$.each(data, function () {
$.each(this, function (key, value) {
alert(value);
});
});
}
Now that I look at this, is it not the array of objects I'm expecting? How can I actually return the string so I can actually see what's really in it and maybe go from there?
**EDIT:
This is my function to get the orders (cut out the crap and showing you an alert)... I call jQuery.Ajax and pass the returned data to displayOrders(data). The orders have a composite property of Items containing a list of Item.
function displayOrders(data) {
$('#gdvOrders tbody').empty();
for (var key in data.d) {
alert(data.d[key].Items);
}
This is what I passed to displayItems, what you see in the alert function. I display the Orders in one table (hiding some columns including the Items), and want to display the Items for each order in another table when they select a row in the orders table. In the function shown above I can write...
data.d[key].OrderId
and it will display as normal. How do I display the properties for each item?
The jQuery.Ajax function is set to content-type: 'application/json; charset=utf-8' and this is where I get the orders from...
[WebMethod]
public static List<Order> GetOrdersByDept(Department department, Filter filter, DateTime? dateFrom = null, DateTime? dateTo = null)
{
return OrderLists.GetOrdersByDepartment((Department)department, (Filter)filter, dateFrom, dateTo);
}
See this is working:
data=[{"Name":"blah","Description":"blah"},{"Name":"blah2","Description":"blah2"}]
data.forEach(function(i,j){
console.log("Name :"+i.Name+" Description :"+i.Description);
})
Using JavaScript, simply use the for .. in loop
for(var i = 0; i < data.length; i++) {
var obj = data[i];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
alert(key + " = " + obj[key]);
}
}
}
Fiddle here - http://jsfiddle.net/XWsvz/
Now that I look at this, is it not the array of objects I'm expecting? How can I actually return the string so I can actually see what's really in it and maybe go from there?
If the object is being returned as a string, you can simply alert it. However, if your function is being passed an unknown object, you can always convert it back to a JSON string and alert it so that you can visualize the structure:
function displayItems(data) {
alert(JSON.stringify(data));
...
}
As a sidenote, I changed the first letter in your function to a lowercase letter to match naming conventions for functions in JavaScript.
Looks like you're close:
function DisplayItems(data) {
console.log('data is: ', JSON.stringify(data));
$.each(data, function (key, arrayElement, index) {
console.log('arrayElement ' + index + ' is: ', JSON.stringify(arrayElement));
$.each(arrayElement, function (key, value) {
console.log('key: ' + key + ' val: ' + value);
});
});
}
http://jsfiddle.net/ux9D8/
With your data this gives me the following output:
data is: [{"Name":"blah","Description":"blah"},{"Name":"blah2","Description":"blah2"}]
arrayElement undefined is: {"Name":"blah","Description":"blah"}
key: Name val: blah
key: Description val: blah
arrayElement undefined is: {"Name":"blah2","Description":"blah2"}
key: Name val: blah2
key: Description val: blah2
I have this currencies.json file:
{
"USD": {
"ValueUSD": 325.33,
"ValueEUR": 344.55,
"PreviousValueUSD": 324.55,
"PreviousValueEUR": 354.55,
},
"EUR": {
"ValueUSD": 325.33,
"ValueEUR": 344.55,
"PreviousValueUSD": 324.55,
"PreviousValueEUR": 354.55,
}
}
I need to parse it into "#content" using jQuery. Can someone help me with a code to do this? I think jSONP is needed because the feed is from another server.
Example for output needed:
<div class="currency">USD, 325.33, 344.55, 324.55, 354.55</div>
<div class="currency">EUR, 325.33, 344.55, 324.55, 354.55</div>
// you will get from server
var obj = $.parseJSON(data); // data contains the string
for (var key in obj) {
$('<div class="currency" />')
.html(key + ', ' + $.map(obj[key], function(val) { return val; })
.join(', ')).appendTo('body');
}
HERE is the code.
$.parseJSON is used to parse the string into the object.
Then for each currency inside object use .map() to map the values.
Join the values into a string separated by ,, append into the div and a currency name.
Resulting div append to the body.
Update (see comments):
If you want to retrieve this data cross-domain use:
$.getJSON('www.domain.com/currencies.json?callback=?', function(data) {
for (var key in data) {
$('<div class="currency" />')
.html(key + ', ' + $.map(data[key], function(val) { return val; })
.join(', ')).appendTo('body');
}
});
Something like this should help (the data parsed from your JSON above is held in the data variable):
var $body = $("body"),
key,
$div,
txt,
innerKey;
for (key in data) {
if (data.hasOwnProperty(key)) {
$div= $("<div></div").addClass("currency");
txt = [key, ", "];
for (innerKey in data[key]) {
if (data[key].hasOwnProperty(innerKey)) {
txt.push(data[key][innerKey]);
txt.push(", ");
}
}
// Remove the trailing comma
txt.pop();
// Set the HTML content of the div and then add to the body
$div.html(txt.join("")).appendTo($body);
}
}
Here's a working example jsFiddle.
well you can access things like:
data.USD.ValueUSD will get you 325.33 so you can do something liek this. pass your data object that you get from your ajax call in ur success func to call this function:
function populateContent(data){
var $currencyDiv = $('<div class="currency"></div>'),
$currencyDiv2 = $currencyDiv.clone();
$currencyDiv.html("USD, "+data.USD.ValueUSD + ", " + data.USD.ValueEUR + ", " + data.USD.PreviousValueUSD + ", " + data.USD.PreviousValueEUR);
//do the same for currencydiv2
//append your new content divs wherever you want
$('body').append($currencyDiv);
}
A more puristic approach that could also help you understand how to iterate through objects (and is browser native and therefore not relying on jQuery)
for(var data in #YOUR_JSON_DATA# ){ // iterate through the JSON nodes
var tmp = data; // store the current node in temporary variable
for(var val in json[data]){ // iterate through the current nodes' children
tmp += ", " + json[data][val]; // this is how you access multidimensional objects. format your output as you like
}
alert(tmp); // see the output. here you could use jquery to write this into your page.
}
I have a servlet which talks with the database then returns a list of ordered (ORDER BY time) objects. At the servlet part, I have
//access DB, returns a list of User objects, ordered
ArrayList users = MySQLDatabaseManager.selectUsers();
//construct response
JSONObject jsonResponse = new JSONObject();
int key = 0;
for(User user:users){
log("Retrieve User " + user.toString());
JSONObject jsonObj = new JSONObject();
jsonObj.put("name", user.getName());
jsonObj.put("time", user.getTime());
jsonResponse.put(key, jsonObj);
key++;
}
//write out
out.print(jsonResponse);
From the log I can see that the database returns User objects in the correct order.
At the front-end, I have
success: function(jsonObj){
var json = JSON.parse(jsonObj);
var id = 0;
$.each(json,function(i,item) {
var time = item.time;
var name = item.name;
id++;
$("table#usertable tr:last").after('<tr><td>' + id + '</td><td width="20%">' + time +
'</td><td>' + name +
'</td></tr>');
});
},
But the order is changed.
I only noticed this when the returned list has large size (over 130 users).
I have tried to debug using Firebug, the "response tab" in Firebug shows the order of the list is different with the log in the servlet.
Did i do anything wrong?
EDIT: Example
{"0":{"time":"2011-07-18 18:14:28","email":"xxx#gmail.com","origin":"origin-xxx","source":"xxx","target":"xxx","url":"xxx"},
"1":{"time":"2011-07-18 18:29:16","email":"xxx#gmail.com","origin":"xxx","source":"xxx","target":"xxx","url":"xxx"},
"2":
,...,
"143":{"time":"2011-08-09 09:57:27","email":"xxx#gmail.com","origin":"xxx","source":"xxx","target":"xxx","url":"xxx"}
,...,
"134":{"time":"2011-08-05 06:02:57","email":"xxx#gmail.com","origin":"xxx","source":"xxx","target":"xxx","url":"xxx"}}
As JSON objects do not inherently have an order, you should use an array within your JSON object to ensure order. As an example (based on your code):
jsonObj =
{ items:
[ { name: "Stack", time: "..." },
{ name: "Overflow", time: "..." },
{ name: "Rocks", time: "..." },
... ] };
This structure will ensure that your objects are inserted in the proper sequence.
Based on the JSON you have above, you could place the objects into an array and then sort the array.
var myArray = [];
var resultArray;
for (var j in jsonObj) {
myArray.push(j);
}
myArray = $.sort(myArray, function(a, b) { return parseInt(a) > parseInt(b); });
for (var i = 0; i < myArray.length; i++) {
resultArray.push(jsonObj[myArray[i]]);
}
//resultArray is now the elements in your jsonObj, properly sorted;
But maybe that's more complicated than you are looking for..
As mentioned by ghayes , json objects are unordered.
There are multiple solutions to this problem.
You can use array and the sort it to get the ordered list.
You can use gson library to get the desired order of elements.
I would prefer the second option as it is easy to use.
As JSONObject is order less and internally uses Hashmap. One way to use it to download the all classes from org.json and use in your project directly by changing the internal HashMap implementation to LinkedHashMap in JSONObject.java file. below is the sorted json files
https://github.com/abinash1/Sorted-Json-Object
I've got some JSON data that is giving me a list of languages with info like lat/lng, etc. It also contains a group value that I'm using for icons--and I want to build a legend with it. The JSON looks something like this:
{"markers":[
{"language":"Hungarian","group":"a", "value":"yes"},
{"language":"English", "group":"a", "value":"yes"},
{"language":"Ewe", "group":"b", "value":"no"},
{"language":"French", "group":"c", "value":"NA"}
]}
And I want to "filter" it to end up like this:
{"markers":[
{"group":"a", "value":"yes"},
{"group":"b", "value":"no"},
{"group":"c", "value":"NA"}
]}
Right now I've got this, using jQuery to create my legend..but of course it's pulling in all values:
$.getJSON("http://127.0.0.1:8000/dbMap/map.json", function(json){
$.each(json.markers, function(i, language){
$('<p>').html('<img src="http://mysite/group' + language.group + '.png\" />' + language.value).appendTo('#legend-contents');
});
});
How can I only grab the unique name/value pairs in the entire JSON object, for a given pair?
I'd transform the array of markers to a key value pair and then loop that objects properties.
var markers = [{"language":"Hungarian","group":"a", "value":"yes"},
{"language":"English", "group":"a", "value":"yes"},
{"language":"Ewe", "group":"b", "value":"no"},
{"language":"French", "group":"c", "value":"NA"}];
var uniqueGroups = {};
$.each(markers, function() {
uniqueGroups[this.group] = this.value;
});
then
$.each(uniqueGroups, function(g) {
$('<p>').html('<img src="http://mysite/group' + g + '.png\" />' + this).appendTo('#legend-contents');
});
or
for(var g in uniqueGroups)
{
$('<p>').html('<img src="http://mysite/group' + g + '.png\" />' + uniqueGroups[g]).appendTo('#legend-contents');
}
This code sample overwrites the unique value with the last value in the loop. If you want to use the first value instead you will have to perform some conditional check to see if the key exists.
How about something more generic?
function getDistinct(o, attr)
{
var answer = {};
$.each(o, function(index, record) {
answer[index[attr]] = answer[index[attr]] || [];
answer[index[attr]].push(record);
});
return answer; //return an object that has an entry for each unique value of attr in o as key, values will be an array of all the records that had this particular attr.
}
Not only such a function would return all the distinct values you specify but it will also group them if you need to access them.
In your sample you would use:
$.each(getDistinct(markers, "group"), function(groupName, recordArray)
{ var firstRecord = recordArray[0];
$('<p>').html('<img src="http://mysite/group' + groupName+ '.png\" />' + firstRecord.value).appendTo('#legend-contents');
}
See this-
Best way to query back unique attribute values in a javascript array of objects?
You just need a variation that checks for 2 values rather than 1.
var markers = _.uniq( _.collect( markers , function( x ){
return JSON.stringify( x );
}));
reference