up vote 0 down vote favorite
share [g+] share [fb]

I'm starting with JSON/Ajax development with Javascript and right now I have a scenario where I'm receiving a JSON string from the server and I want to build an object on the client side. My server output is this:

[{"username":"user","mine":"[{"id":"1","artist":"Pearl Jam","name":"Rival"},{"id":"2","artist":"Pearl Jam","name":"Lukin"}]","default":"50"}]

On the JS side I'm doing this:

$.getJSON('?action=load',
        function(data)
        {

              window.User = data[0];
        });

I can print window.User.username and window.User.default. However I was expecting I could do something like alert(window.User.mine[0].id) as well, but it prints [ (the first character of the songs array, so I'm assuming it is being interpreted as a string). What I'm I doing wrong here?

Thanks a lot in advance.

link|improve this question

76% accept rate
feedback

3 Answers

up vote 2 down vote accepted
"[{"id":"1","artist":"Pearl Jam","name":"Rival"},{"id":"2","artist":"Pearl Jam","name":"Lukin"}]"

should be this

[{"id":"1","artist":"Pearl Jam","name":"Rival"},{"id":"2","artist":"Pearl Jam","name":"Lukin"}]

The quotes around the arrays make them strings

link|improve this answer
feedback

Use:

window.User.mine.[0].id

(after fixing your JSON as suggested...)

link|improve this answer
No, there shouldn't be a period before the array index. – Guffa Dec 13 '11 at 19:11
feedback

Your JSON is malformed, so you get a string and not an array, thats the reason.

Your JSON should look like this:

[{"username":"user","mine":[{"id":"1","artist":"Pearl Jam","name":"Rival"},{"id":"2","artist":"Pearl Jam","name":"Lukin"}],"default":"50"}]

and then you will get the expected result

link|improve this answer
Hmm yes, it is indeed – fge Dec 13 '11 at 19:01
@fge: Even the syntax highlighter agrees on that ;) – missingno Dec 13 '11 at 19:02
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.