How to loop through json array using jquery.each() - javascript

I was trying to show my json data using jquery.each().
now this is the json
var json =
[
{"id":"1","tagName":"apple"},
{"id":"2","tagName":"orange"
}]
then i can show it
$.each(json, function(idx, obj) {
alert(obj.tagName);
});
But my json is
{
"Message": "Success",
"Code": "200",
"Payload": [
{
"year": "2015",
"month": "6",
"fileCount": "985",
"totalFileSize": "2820"
},
{
"year": "2015",
"month": "7",
"fileCount": "15347",
"totalFileSize": "66549"
}
]
}
Now I need to read the data inside the Payload. please help me with

Very simply. Payload is property of the object that you have provided, which can be accessed like this: json.Payload. So you should pass it as the first argument to $.each() method. Here you go:
$.each(json.Payload, function(idx, obj) {
console.log(obj);
});
http://jsfiddle.net/2wxwkxbd/

You can also use
$.map(array,function(obj,index){
console.log(obj)
});
for iterating through an array

Related

Parse nested JSON Response Javascript

I know there are several threads on this subject but I've looked through over 30 threads without success.
I have managed to parse a JSON response so it looks like this:
{
"1": {
"id": "1",
"name": "Fruit",
.
.
.
"entities": {
"1": {
"id": "1",
"name": "blue bird",
.
.
.
"status": "1"
},
"2": {
using this code
let json = JSON.parse(body);
console.log(json);
Now I want to access the "id", "name" etc. AND the "id" and "name" for the "entities" tag.
So far I have tried:
console.log(json[0]);
console.log(json.id);
which both returns undefined
I have also tried
console.log(json[0].id);
which gives an error
Any ideas?
In this instance, your first key is 1, so you can access it with json[1].
const json = {
"1": {
"id": "1",
"name": "Fruit"
},
"2": {
"id": "2",
"name": "Veggies"
}
};
console.log(json[1]);
In this json, you can reach the id by
json.1.id
But I think that first of all your json is not correctly written, you should have something like
{
"elements": [
{ "id" : 1, "name" : "fruit" },
{ "id" : 2, "name" : "vegetable" }
]
}
like that, json.elements is a collection/array, and you can loop, count, or any other things you will not be able to do because your json looks like a super heavy list of different properties ( he doesn't know that json.1 and json.2 are the same type of objects.
const jsonData = JSON.parse(body);
for (const i in jsonData) {
for (const j in jsonData[i]) {
console.log('${i}: ${jsonData[i][j]}');
}
}

Converting strings to intergers in JSON using JavaScript

I have the following json
{
"Title": "Test",
"StartDate": {
"Month": "3",
"Year": "1973"
},
"EndDate": {
"Month": "4",
"Year": "1974"
}
}
I want Month and Year values from StartDate and EndDate to be without quotes, like this:
{
"Title": "Test",
"StartDate": {
"Month": 3,
"Year": 1973
},
"EndDate": {
"Month": 4,
"Year": 1974
}
}
EDIT
I'm not creating the json, with JSON.stringify(). My JSON is created by Form Builder module from Angular 2, despite the fact that I'm setting it's type to number, after I change the value, the value gets quotes.
Before saving your JSON, use the parseInt() functions to convert your values into integers. This will remove the quotes.
JSON.stringify({
Month: parseInt( value , 10);
})
See this answer
EDIT
If you made that JSON Object earlier in your JavaScript code, go for #Adrian Lambertz's answer. If you got that JSON as a String from somewhere else and want to convert it, read my answer :
My original answer
Say you got this JSON as a string in your JavaScript code, you could convert the desired values to integers like this :
var events = JSON.parse(JSONStringYouWantToConvert);
// if the JSON String is an array of events that all have a Title, a StartDate and an EndDate
for (var i = 0; i < events.length; i++) {
// else, forget about the loop and the [i] index, the concept remains the same
events[i].StartDate.Month = parseInt(events[i].StartDate.Month);
events[i].StartDate.Year = parseInt(events[i].StartDate.Year);
events[i].EndDate.Month = parseInt(events[i].EndDate.Month);
events[i].EndDate.Year = parseInt(events[i].EndDate.Year);
}
// make a JSON String that wont have the quotes around the Month and Year numbers
var JSONStringConverted = JSON.stringify(events);
Just convert the strings to numbers.
This code is just an example, you can adapt it to whatever your object structure is.
function normalize(target) {
for (const date of ['StartDate', 'EndDate']) {
for (const item of ['Month', 'Year']) {
target[date][item] = Number(target[date][item]);
}
}
}
I can not see the order from which data the result is expeceted, so here two versions.
Object -> JSON (-> Object)
This works with JSON.stringify
and a replacer function for creating numbers for certain keys, like Month and Year.
var dataObj = { "Title": "Test", "StartDate": { "Month": "3", "Year": "1973" }, "EndDate": { "Month": "4", "Year": "1974" } },
jsonStr = JSON.stringify(dataObj, function (k, v) {
return ['Month', 'Year'].indexOf(k) !== -1 ? +v : v;
}),
parsed = JSON.parse(jsonStr);
console.log(jsonStr);
console.log(parsed);
JSON -> Object
This works with JSON.parse
and a reviver function for creating numbers for certain keys, like Month and Year.
var jsonStr = '{ "Title": "Test", "StartDate": { "Month": "3", "Year": "1973" }, "EndDate": { "Month": "4", "Year": "1974" } }',
parsed = JSON.parse(jsonStr, function (k, v) {
return ['Month', 'Year'].indexOf(k) !== -1 ? +v : v;
});
console.log(parsed);

Can't retrieve data from JSON in Javascript. The json is passed from php

I have a problem and i search for a solution, but i can't find it. I have this Json:
[
{
"name": "Pippo (74)",
"price": "1",
"latitudine": "10.32562",
"longitudine": "44.8003686"
},
{
"name": "pluto",
"price": "2",
"latitudine": "10.32562",
"longitudine": "44.8003686"
}
]
I want retrieve data from the Json (named msg):
num = msg.length;
document.write (num);
document.write (msg[0].name);
But it don't work! Can you help me?
You might use this parse json.
http://api.jquery.com/jquery.parsejson/
var output = jQuery.parseJSON( '[
{
"name": "Pippo (74)",
"price": "1",
"latitudine": "10.32562",
"longitudine": "44.8003686"
},
{
"name": "pluto",
"price": "2",
"latitudine": "10.32562",
"longitudine": "44.8003686"
}]' );
var list = output.data;
$.each(list,function(i,item){
console.log(item.name);
});
you can use var parsedMsg = JSON.parse(msg); to transform to a pure JS object. Then run your script. You also have a typo in 'length'
A shot in the dark here, but guessing your JSON needs to be parsed:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
var parsedMsg = JSON.parse(msg);
then you can do whatever you like with the data:
num = parsedMsg.length;
console.log(num);
console.log(parsedMsg[0].name);

How can I populate a table with part of a JSON

I have a JSON being returned an I want to take the last 8 elements of the JSON and make a table. The table builds the way I expect it to but I'm getting undefined as the result value.
Here is the code for the getJSON, an edited down return and the table.
$.getJSON("loadloads.php", function(data){
[{
"value": {
"lineNumber": "258640",
"TypeId": "1",
"StopNumber": "1",
"ReferenceNo": "0002325063",
"LocationId": "3",
"SLN": "227311",
"LoName": "Elk GAF Materials Corp - Shafter",
"Type": "Shipper"
}
}, {
"value": {
"lineNumber": "258641",
"TypeId": "2",
"StopNumber": "2",
"ReferenceNo": "682383",
"LocationId": "205697",
"SLN": "227311",
"LoName": "RWC Building Products - Albuquerque",
"Type": "Consignee"
}
}
]
var table_obj = $('table');
$.each(data, function(index,value){
table_obj.append($('<tr><td>'+value.SLN+'</td><td >'+value.Type+'</td><td>'+value.StopNumber+'</td><td>'+value.LoName+'</td><td>'+value.ReferenceNo+'</td><td class="hide">'+value.TypeId+'</td><td class="hide">'+value.Locationid+'</td><td class="hide">'+value.lineNumber+'</td></tr>'));
The name you gave your variable "value" is confusing you. You still need to reference the "value" key within your object that just happens to be named value.
'+value.value.SLN+
Try this way .
value.value.SLN
Try this. All properties are inside value so you should try value.value
$.each(data, function(index, v){
var value = v.value;
table_obj.append($('<tr><td>'+value.SLN+'</td><td >'+value.Type+'</td><td>'+value.StopNumber+'</td><td>'+value.LoName+'</td><td>'+value.ReferenceNo+'</td><td class="hide">'+value.TypeId+'</td><td class="hide">'+value.Locationid+'</td><td class="hide">'+value.lineNumber+'</td></tr>'));
}
try this
for (var i in data)
console.log(data[i].value);
if it will output in console result, just use it as data[i].value.field

how to use for each with mustache javascript?

i have some json objects and some of them have some other objects inside them.
if i leave only the json obj that don't have other obj inside them and then apply the template, everything goes well, i get, in this case 3 li elements.
but if i grab the original json obj the results are a bit wired. I believe i need to do a each statement to iterate through each sub json obj from inside each main one
maybe i am a bit confuse so here is some code.
i have some json data like this:
{
"msg_id":"134",
"message":"Nick",
"comment":[
{
"com_id":"9",
"comment":"test",
},
{
"com_id":"10",
"comment":"testtt",
},
{
"com_id":"11",
"comment":"testtttt",
}]
},
{
"msg_id":"134",
"message":"Nick",
},
{
"msg_id":"134",
"message":"Nick",
}
and i am trying to arive at something like this:
Nick
test
testtt
testtttt
Nick
Nick
i've created a template like this:
function messagesTamplate(data)
{
$.each(data, function(index, obj)
{
msg += template.replace( /{{message}}/ig , obj.message );
if(obj.comment) {
$.each(obj.comment, function(key, val)
{
msg += template.replace( /{{comment}}/ig , val.comment );
});
}
});
return msg;
}
then i just append this to the main ul.
thanks
data needs to be an array (see the enclosing [])
var data = [{
"msg_id": "134",
"message": "Nick",
"comment": [{
"com_id": "9",
"comment": "test",
}, {
"com_id": "10",
"comment": "testtt",
}, {
"com_id": "11",
"comment": "testtttt",
}]
}, {
"msg_id": "134",
"message": "Nick",
}, {
"msg_id": "134",
"message": "Nick",
}]
is just this in mustache templates:
{{#data}} //loop through all data
{{message}} //pick out the "message" per iteration
{{#comment}} //loop through all comments in an iterated item
{{comment}} //pick out the comment
{{/comment}}
{{/data}}

Categories

Resources