How to select json item from the array

From the below JSON, how can I retrieve title from the note and notes using a for loop and ajax to retrieve?

{
"infos": { "info": [ { "startYear": "1900", "endYear": "1930", "timeZoneDesc": "daweerrewereopreproewropewredfkfdufssfsfsfsfrerewrBlahhhhh..", "timeZoneID": "1", "note": { "notes": [ { "id": "1", "title": "Mmm" }, { "id": "2", "title": "Wmm" }, { "id": "3", "title": "Smm" } ] }, "links": [ { "id": "1", "title": "Red House", "url": "" }, { "id": "2", "title": "Joo Chiat", "url": "" }, { "id": "3", "title": "Bake", "url": "" } ] }

I tried out the code below but it doesn't work - it either says:

is null

not an object

length is null

r not an object

var detail = eval(xmlhttprequest.responseText)
var rss = detail.infos.info
for(var i = 0; i<rss.length; i++) startyear += rss[i].startyear
4

4 Answers

Use

for (i = 0; i < 3; i++) { alert(JSON.infos.info[0].note.notes[i].title);
}

TRY IT HERE: JSFIDDLE WORKING EXAMPLE

BTW your JSON is not valid. Use this JSON:

var JSON = { "infos": { "info": [ { "startYear": "1900", "endYear": "1930", "timeZoneDesc": "daweerrewereopreproewropewredfkfdufssfsfsfsfrerewrBlahhhhh..", "timeZoneID": "1", "note": { "notes": [ { "id": "1", "title": "Mmm" }, { "id": "2", "title": "Wmm" }, { "id": "3", "title": "Smm" } ] }, "links": [ { "id": "1", "title": "Red House", "url": "" }, { "id": "2", "title": "Joo Chiat", "url": "" }, { "id": "3", "title": "Bake", "url": "" } ] } ] }
}

EDIT:

Here is what you want:

var infoLength= JSON.infos.info.length;
for (infoIndex = 0; infoIndex < infoLength; infoIndex++) { var notesLength= JSON.infos.info[infoIndex].note.notes.length; for (noteIndex = 0; noteIndex < notesLength; noteIndex++) { alert(JSON.infos.info[infoIndex].note.notes[noteIndex].title); }
}
11

Putting your json into an var called obj, use the following:

obj.infos.info[0].note.notes[0].title
1

Well the "path" to the JSON notes array-like object is:

json.infos.info[0].note.notes;

So you could do something like:

var notes = json.infos.info[0].note.notes;
var titles = [];
for (var i = 0, len = notes.length; i < len; i++)
{ titles.push(notes[i].title);
}
alert('titles is: ' + titles.join(', '));

Fiddle:


Are you using jQuery? ;-)

// Assuming your using "success" in ajax response
success: function(json)
{ var titles = $(json.infos.info[0].note.notes).map(function() { return this.title; }).get(); alert(titles.join(', '));
}
4

First count the length of notes

var len = jsonobject.infos.info.note.notes.length;

Then loops through and get

var title = jsonobject.infos.info.note.notes[i].title;

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like