2

I have the following JSON Object:

[{"id":"123","username":"test"}]

I want to parse username using javascript so i did this

var content = '[{"id":"123","username":"test"}]
obj = JSON.parse(content)
alert(obj.username)

I get an alert: undefined

I've tried parsing the JSON without the [ ] and it worked

For example:

var content = '{"id":"123","username":"test"}'
obj = JSON.parse(content)
alert(obj.username)

My question would be how would i parse the JSON with the [ ] tags around it? Thank you!

Nat Ritmeyer
5,6868 gold badges49 silver badges60 bronze badges
asked Oct 24, 2012 at 19:45

2 Answers 2

10

That's because [] makes it an array. Try alert(obj[0].username).

If you changed your JSON to look like this...

[ {"id":"123","username":"test"}, {"id":"456","username":"test 2"}]

Then alert(obj[1].username) would be test 2, and alert(obj[0].username) would be test.

answered Oct 24, 2012 at 19:46
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I had tried using alert(obj[1].username) but it didn't work. I was wondering why it didn't. Thank you very much!
2

The undefined error you get in the first case is because the JSON represents an ARRAY with a single object in it. In order to access the username you would need alert(obj[0].username)

answered Oct 24, 2012 at 19:47

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.