Reputation: 530
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
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
Reputation: 12036
I see few problems:
,
and strings in JSON should be quoted.obj.users
, and your object, even if it would have that ,
, does not have users at all.Upvotes: 1
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