0

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.

0

3 Answers 3

2
"[{"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

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

Comments

2

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

1 Comment

@fge: Even the syntax highlighter agrees on that ;)
0

Use:

window.User.mine.[0].id

(after fixing your JSON as suggested...)

1 Comment

No, there shouldn't be a period before the array index.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.