9

Possible Duplicate:
jquery reading nested json

I would really like to have a hard and fast method to loop through multiple records in JSON, each with potentially deep nesting. I simply want to output to a table.

I am unsure of what arguments need to be passed through the function() for either $.each() or for the javascript methodology of $.ajax() success. All examples seem to use generic words "data" or "obj" but those confuse me - are they built-in functional arguments or can I name them whatever I want like:

$.each(foo, function(bar){

});

And how can I keep track of where I am in the loop / nest?

I would prefer to use JQuery, but I should also know the straight-forward JavaScript method to do so. And I'd also like to know if it's possible without a hundred lines of code.

With this JSON as an example:

{
  date: " 2012-10-18 16:58:35.104576",
  data: [{
    title: "The Princess Bride",
    rating: "PG",
    length: 128,
    stars: [
      "Gary Elwes",
      "Robin Wright",
      "Christopher Guest"
    ]

  }, {
    title: "This is Spinal Tap",
    rating: "R",
    length: 105,
    stars: [
      "Christopher Guest",
      "Michael McKean",
      "Harry Shearer"
    ]
  }]
}

I can't find any useful examples that include nested JSON, even here in the StackOverflow.

what's the most efficient way to loop through and assign each element to a table cell? The HTML output is not important - I know how to make a table... How do I get the "stars"?

When I use the Chrome console and simply $.getJSON('/example'); I get the entire JSON returned in the responseText, starting with "{"date":"2012-10-18 ,"data": [{"title": "The Princess Bride", However in neither the JSON docs, the JQuery docs on $.getJSON, nor in any JavaScript examples can I find a reference to responseText. So, I'm lost. What argument does $.getJSON need to objectify the responseText?

Community
  • 1
  • 1
Jon Mitten
  • 1,965
  • 4
  • 25
  • 53
  • Regarding your last comment, you'll want to parse it. Try `var myData = JSON.parse(responseText);` You might find it helpful to output it to the console, too: `console.log(myData)` Then you can do something like `var someStars = myData.data[0].stars;` Let me know if you have any questions about looping through your data. – IanW Oct 22 '12 at 22:29

1 Answers1

14

try

obj.data[0].stars      // Will get you the stars in the 1st Object

obj.data[0].stars[0]   // Gary Elwes

FIDDLE

To iterate thru the Stars object You can try this

$.each(obj.data , function(key , value){ // First Level
    $.each(value.stars , function(k , v ){  // The contents inside stars
        console.log(v)
    });        

});

UPDATED FIDDLE

EDIT

 $.ajax({
      // Parameters 

      success : function(obj){
            $.each(obj.data , function(key , value){ // First Level
                 $.each(value.stars , function(k , v ){  // The contents inside stars
                     console.log(v)
                 });     
            });
      }
  });
Sushanth --
  • 55,259
  • 9
  • 66
  • 105
  • What if the JSON is coming in via AJAX? How can I assign var obj via AJAX? – Jon Mitten Oct 22 '12 at 21:50
  • 1
    Check edited post.. You object will be in the callback of your Ajax request – Sushanth -- Oct 22 '12 at 22:33
  • When I do: ` $.ajax({ url:'/example', dataType:'json', success: function(obj){ $.each(obj.data, function(key, value){ $.each(value.stars, function(k,v){ alert(v); }); }); } }); ` I get `Uncaught TypeError: Cannot read property 'length' of undefined` I wish I could figure out how to debug this myself, but what am I doing wrong? – Jon Mitten Oct 22 '12 at 22:49
  • Check the console section for any errors .. What does the request and response show in the console.. Also set type: 'POST' for your ajax request – Sushanth -- Oct 22 '12 at 22:51
  • it's the console saying `Uncaught TypeError: cannot read property 'length' of undefined`, and expanding the error in Chrome console there's an `(anonymous function)` in my JSON script on the line with `$.each(value.stars, function(k,v){` – Jon Mitten Oct 22 '12 at 22:58
  • is there an index missing from this function? – Jon Mitten Oct 22 '12 at 22:59
  • 1
    Check the request and response data... Also try commenting your loops and try console.log(obj) .. What do you see?? – Sushanth -- Oct 22 '12 at 22:59
  • This is cool: the console.log(obj); with the request of 'POST' results in a 404 error, changing to 'GET' comes back with: `data:Array[7]` (using live data, there are 7 records) Each index displays `> 0:Object > 1:Object` and so-on. However, I'm still getting `Uncaught TypeError: Cannot read property 'length' of undefined` when I restore the second each loop, `$.each(value.stars, function(k,v){alert(v);}); because, as it turns out, the live data uses an underscore before the stars Array. So, this error is resulting from a typo. Changing `stars` to `_stars` alleviates this issue, alerts ensue. – Jon Mitten Oct 22 '12 at 23:23
  • @Sushanth-- Thanks for your answer. It works for me. I have tried many solution but your solution works. uprated. Thanks – vrajesh Oct 03 '18 at 20:05