Looping through JSON data in javascript not working - javascript

I have some JSON data being returned from an AJAX call. I then need to parse this data in javascript.
The data looks like so:
[
{
"id": "23",
"date_created": "2016-05-12 14:52:42"
},
{
"id": "25",
"date_created": "2016-05-12 14:52:42"
}
]
Why is it when i run this code on the data that i get multiple undefined's?
(var json being the variable holding my json data)
for(var i = 0; i < json.length; i++) {
var obj = json[i];
console.log(obj.id);
}
However if i assign the json directly to the variable like so:
var json = [
{
"id": "23",
"date_created": "2016-05-12 14:52:42"
},
{
"id": "25",
"date_created": "2016-05-12 14:52:42"
}
];
Then it works fine!
Any ideas guys? Thanks

Make sure the JSON you're getting is not just stringified JSON. In that case do JSON.parse(json_string) and then loop and more processing.
Example:
var string_json = '[{"a":1},{"b":2}]'; // may be your API response is like this
var real_json = JSON.parse(string_json); // real_json contains actual objects
console.log(real_json[0].a, real_json[1].b); // logs 1 2

It is not a JSON that, you are using.
It's an object array.
When you get JSON, parse that JSON using method JSON.parse.
Assign this JSON to a variable and then use iteration over it...
Ex:
var json ='[{"id": "23","date_created": "2016-05-12 14:52:42"},{"id": "25","date_created": "2016-05-12 14:52:42"}]';
var parsedJson = JSON.parse(json);
for(var i = 0; i < parsedJson.length; i++) {
var obj = parsedJson[i];
console.log(obj.id);
}

Related

Iterating and printing a JSON with no initial key and multiple entries

How would you go about iterating through a JSON object no initial key but multiple entries?
var json_no_key =
{
{"txid" : "1",
"amount" : "100",},
{"txid" : "2",
"amount" : "50"},
};
I have tried using other methods whereby each element would have a key itself such as
for(var i = 0; i < transaction.vin.length; i++)
{
var my_json = transaction.vin[i];
console.log(my_json[i])
for(var j = 0; j < my_json.length; j++)
{
console.log(my_json[j]);
}
}
but this relies on there being an initial key.
The reasoning for this format is due to the nature of how a api outputs data.
I echo with #CherryDT. The object json_no_key is not a valid JSON format. Please check the format in https://jsonlint.com/. Instead of an object, convert it into an array so that you could do the following using a simple forEach:
const a =[
{
"txid": "1",
"amount": "100",
},
{
"txid": "2",
"amount": "50"
},
];
a.forEach(element=>{
console.log(element.txid);
console.log(element.amount);
})

How do i iterate through JSON array in javascript?

I have a json data coming from rest in following format:
{
"status_code": 200,
"data": {
"units": -1,
"unit_reference_ts": null,
"tz_offset": -4,
"unit": "day",
"countries": [{"country": "IN", "clicks": 12}]},
"status_txt": "OK"
}
I want to access the countries part and need to generate data in format like
{"IN":12, ......}
I dont know how to iterate through javascript, JSON array? Please help i am confused between methods which is the best & easiest that will work throughout the JSON?
I tried this:
$.each(response.countries, function(key, value) {
console.log(value.country + ": " + value.clicks);});
but it is showing me type error e is undefined...
Make sure you parse your JSON first (var data = JSON.parse(json)), then use a simple loop:
var obj = {};
for (var i = 0, l = data.data.countries.length; i < l; i++) {
var tmp = data.data.countries[i];
obj[tmp.country] = tmp.clicks
}
console.log(obj); // { IN: 12, UK: 123 }
DEMO
Since (from your edit) you're using jQuery, you'll probably need to do this (note that jQuery automatically parses JSON data if you retrieve it using one of its AJAX methods):
var obj = {};
$.each(response.data.countries, function(key, value) {
obj[value.country] = value.clicks;
});
If you want a string instead of an object, just JSON.stringify the obj:
var json = JSON.stringify(obj);
DEMO

Access Data from Ajax Call Jquery

I am using Jquery Ui Autocomplete.
The problem I have is the data that is being returned from my api.
"{"d":{"results":[],"facets":{"facet_counts":{"Town":{"":0,"londonderry":136914,"london bridge":1,"london":8983316,"london colney":1}}},"__solr_time":3473457,"__ser_time":1564,"__t_time":1421,"__count":9120232,"__max_score":1.0}}"
I have run it through an online parser and it is valid, but I don't know how to access the list of towns with the corresponding number next to it.
Any help would be appreciated
I was able to access the Town "name" and number using:
var test = {
"d": {
"results": [],
"facets": {
"facet_counts": {
"Town": {
"": 0,
"londonderry": 136914,
"london bridge": 1,
"london": 8983316,
"london colney": 1
}
}
},
"__solr_time": 3473457,
"__ser_time": 1564,
"__t_time": 1421,
"__count": 9120232,
"__max_score": 1
}
}
for(var prop in test.d.facets.facet_counts.Town){
console.log(prop);
console.log(test.d.facets.facet_counts.Town[prop]);
}
Just run JSON.parse() on the string and then pull out the Town node.
var string; // the data string returned by API.
var dataObj = JSON.parse(string);
var Town = dataObj.d.facets.facet_counts.Town;
// access the properties as needed
var londonCount = Town.london;
var londonBridgeCount = Town['london bridge']; // need to use bracket notation to get this one

Extract from Ajax response

I have an ajax call that returns JSON data (Data Attached).
After converting the data into String, this is how it looks like:
{
"shipments":[
{
"companyName":"TriStar Inc.",
"shipmentDate":null,
"transMode":"NDAY",
"paid":true,
"delDate":null,
"custRefInfo":{
"customerName":"DAISY N.",
"customerZip":"90544"
},
"orderStatus":true
},
{
"companyName":"Carbo Box",
"shipmentDate":null,
"transMode":"COUR",
"paid":true,
"delDate":null,
"custRefInfo":{
"customerName":"TOM K",
"customerZip":"07410"
},
"orderStatus":true
}
]
}
Now when I print the JSON response in Firefox, it looks like:
[Object { companyName="TriStar Inc.", shipmentDate=null, transMode="NDAY", more...}, Object { companyName="Carbo Box", shipmentDate=null, transMode="COUR", more... } ]
My question is, how do I extract companyName and customerName field out of this response. The following isnt working:
load: function(response){
for(var i in response){
console.log(response.shipments[i].companyName);
}
if you get a string that is json, you need to parse it first.
var obj = JSON.parse(jsonString);
now you have a proper object literal, and you can access it normally
var shipments = obj.shipments;
shipments is now a javascript array...
for(var i = 0; i < shipments.length; i++){
console.log(shipments[i].companyName);
}
note you should not use the for(var i in x) construct on arrays.
response.shipments[i].companyName

Use a JSON array with objects with javascript

I have a function that will get a JSON array with objects. In the function I will be able to loop through the array, access a property and use that property. Like this:
Variable that I will pass to the function will look like this:
[{
"id": 28,
"Title": "Sweden"
}, {
"id": 56,
"Title": "USA"
}, {
"id": 89,
"Title": "England"
}]
function test(myJSON) {
// maybe parse my the JSON variable?
// and then I want to loop through it and access my IDs and my titles
}
Any suggestions how I can solve it?
This isn't a single JSON object. You have an array of JSON objects. You need to loop over array first and then access each object. Maybe the following kickoff example is helpful:
var arrayOfObjects = [{
"id": 28,
"Title": "Sweden"
}, {
"id": 56,
"Title": "USA"
}, {
"id": 89,
"Title": "England"
}];
for (var i = 0; i < arrayOfObjects.length; i++) {
var object = arrayOfObjects[i];
for (var property in object) {
alert('item ' + i + ': ' + property + '=' + object[property]);
}
// If property names are known beforehand, you can also just do e.g.
// alert(object.id + ',' + object.Title);
}
If the array of JSON objects is actually passed in as a plain vanilla string, then you would indeed need eval() here.
var string = '[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]';
var arrayOfObjects = eval(string);
// ...
To learn more about JSON, check MDN web docs: Working with JSON
.
This is your dataArray:
[
{
"id":28,
"Title":"Sweden"
},
{
"id":56,
"Title":"USA"
},
{
"id":89,
"Title":"England"
}
]
Then parseJson can be used:
$(jQuery.parseJSON(JSON.stringify(dataArray))).each(function() {
var ID = this.id;
var TITLE = this.Title;
});
By 'JSON array containing objects' I guess you mean a string containing JSON?
If so you can use the safe var myArray = JSON.parse(myJSON) method (either native or included using JSON2), or the usafe var myArray = eval("(" + myJSON + ")"). eval should normally be avoided, but if you are certain that the content is safe, then there is no problem.
After that you just iterate over the array as normal.
for (var i = 0; i < myArray.length; i++) {
alert(myArray[i].Title);
}
Your question feels a little incomplete, but I think what you're looking for is a way of making your JSON accessible to your code:
if you have the JSON string as above then you'd just need to do this
var jsonObj = eval('[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]');
then you can access these vars with something like jsonObj[0].id etc
Let me know if that's not what you were getting at and I'll try to help.
M
#Swapnil Godambe
It works for me if JSON.stringfy is removed.
That is:
$(jQuery.parseJSON(dataArray)).each(function() {
var ID = this.id;
var TITLE = this.Title;
});
var datas = [{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}];
document.writeln("<table border = '1' width = 100 >");
document.writeln("<tr><td>No Id</td><td>Title</td></tr>");
for(var i=0;i<datas.length;i++){
document.writeln("<tr><td>"+datas[i].id+"</td><td>"+datas[i].Title+"</td></tr>");
}
document.writeln("</table>");

Categories