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.
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 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 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'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?