views:

50

answers:

1

Hi,

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.

+2  A: 

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).

Marc B
I am looking something like for loop which loops through it and gives us the variable. I apologize, i am new to computer programming.. and have lots to learn.
Kate Gomes
I use JQuery a lot, but if there is one thing I avoid using it for, it is loops. .each() loop does not scale well! Anyway good info +1.
Anders
'book' property is an array hence we need to access through its index:var title = booklist[bookID]['book'][0]['title']['name'];
Marimuthu Madasamy