3

Im trying to loop through a json files' object array to access its variables' keys and values and append them to list items using jquery's getjson and each.

I think the solution should be similar to the solution in this article... but I cant seem to make it work and display the results at all... Any help would be very much appreciated!

Jquery, looping over a json array

$.getJSON('data/file.json', function(data)
 { 
   var data = [];
   $(data).each(function(idx, obj)
    { 
     $(obj).each(function(key, value)
      {console.log(key + ": " + value);}
     }
   }
);

The json data is formatted like this:

[{
    "name": "Name",
    "street_address1": "XYZ Road",
    "street_address2": null,
    "city": "New York",
    "zip": 10038,
    "phone": 2122222222 ", 
    "description ": "About xyz..."
 }, 
 { next listing... }]

And the html should be formatted like this:

 Name: Name

 Address: XYZ Road
          Floor #2
          City, State 10001

 Description: About xyz...
0

2 Answers 2

12

var data = [];

You are replacing data with a blank array, thus destroying your data when this is ran. Remove this line, and it should work.

EDIT: There are also some syntax errors in your code. You need to close the parenthesis after each of the each statements. It should look like this:

$.getJSON('data/file.json', function(data){ 
    $(data).each(function(idx, obj){ 
        $(obj).each(function(key, value){
            console.log(key + ": " + value);
        });
    });
});

EDIT 2: data and obj aren't jQuery objects, they are just normal objects. You need to use $.each compared to $().each for this.

$.getJSON('data/file.json', function(data){ 
    $.each(data, function(idx, obj){ 
        $.each(obj, function(key, value){
            console.log(key + ": " + value);
        });
    });
});
Sign up to request clarification or add additional context in comments.

4 Comments

Removed that and still nothing displays...?
@obj-ified: That's weird. There's nothing in your console?
Hmm -- was getting 'missing paren after argument list in firebug console. I think the each callback functions werent being properly closed. I modified it -- but am now getting a listing of undefined objects --
@obj-ified: data and obj aren't jQuery objects, try using $.each instead of $().each. Check the 2nd edit in my answer.
0
$.getJSON('data/file.json', function(data){ 
    $.each(data,function(idx, obj){ 
        $.each(obj, function(key, value){
            console.log(key + ": " + value);
        });
    });
});

2 Comments

obj isn't a jQuery object, you want to use $.each on that too.
Using $(obj) will actually wrap the object in an array, which will not help here.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.