Reputation: 21
I have a json output that looks like this.
{
"38467": {
"name": "Tony Parker",
"book": [
{
"title": {
"name": "MediaWorks"
},
},
],
}
"59678": {
"name": "Ray Thomas",
}
}
Actually json output is a lot bigger list. But I want to only save author's name and their publisher. I want save multiple individual records for a single model.
I am using jquery to assign input elements their values.
$('#Author' + i + 'Title').val(response...);
But it is not working.
I appreciate any help.
Thanks.
Upvotes: 2
Views: 8460
Reputation: 360572
JSON is just javascript data - a javascript object. Assign the "decoded" JSON data to a variable (say var dat
), then you can access members the normal object/array away: dat[38467]['name']
is Tony Parker
and so on.
comment update:
once you've decoded/stored the data, you can use a regular javascript foreach loop to go over it:
for (var bookID in booklist) {
var author = booklist[bookID]['name'];
var title = booklist[bookID]['book'][0]['title']['name'];
// ...do stuff here...
}
There's nothing magical about JSON, it's just javascript data packed up for easy/clean transmission. Of course, if you're using a framework such as jQuery or MooTools, you'd be better off using their own .each()
operators, otherwise you'll get various bits of useless fluff from the for()
loop.
edit: fixed code sample as per marimuthu's comment (good catch, thanks).
Upvotes: 2