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!

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.

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)

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.