0

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.

2
  • Have you tried settings debug breakpoints within developer console on every line? This would tell you which piece specifically is not behaving as expected. Commented Oct 27, 2013 at 0:18
  • use jsonlint.com to validate your json Commented Oct 27, 2013 at 1:51

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

This one solves the matter. I can access the attributes, but as @Corey said, I can't do an each for array. I'll find that out in a while. Thanks a bunch guys!
1

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.

2 Comments

OK. I've updated my question. in regards to your comment. But still nothing.
@rolodex still obj.name is not defined... use $.each(obj, function(i,o){console.log(o.name)}) and quote indexes in json.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.