rolodex
rolodex

Reputation: 530

Create dynamic nested list from JSON using jQuery

I have a problem understanding this problem. I have this json in a file called list.json for testing purpose. I will be getting this list generated by server later on.

[
{
    name    : "ABC",
    id      : "link_abc"
},
{
    name    : "DEF",
    id      : "link_def"
},
{
    name    : "GHI",
    id      : "link_ghi"
},
{
    name    : "JKL",
    id      : "link_jkl"
}

]

And here's my javascript to display the list in <li> format.

$(function(generate_list_from_JSON){
$('a[href="#state"]').click(function(){
    $.getJSON("scripts/list.json", function (obj){
        $.each(obj.name, function (key, value){
            alert(key);
            })
        });
    });
});

The problem is, there's nothing displayed, even in console. How do I trap what's sending and what's receiving? I tried console.log() but still blank.

Upvotes: 0

Views: 730

Answers (3)

Corey
Corey

Reputation: 1133

You cannot do an each on obj.name. obj is an array. Arrays do not have a property named "name" and therefore you'll never enter the loop.

Just loop through obj[0] to obj[obj.length-1].

Upvotes: 1

Flash Thunder
Flash Thunder

Reputation: 12036

I see few problems:

  • Your JSON object is invalid. It is an array of objects but first two objects are not separated with , and strings in JSON should be quoted.
  • In your javascript code, you are refering to obj.users, and your object, even if it would have that ,, does not have users at all.

Upvotes: 1

Terry Roe
Terry Roe

Reputation: 1134

JSON requires quotation marks around the attribute names. So you need to do something like this:

[
{
    "name"    : "ABC",
    "id"      : "link_abc"
},
...
]

JavaScript objects don't require the attribute names to be quoted, but JSON does.

HTH

Upvotes: 2

Related Questions