mormaii2
mormaii2

Reputation: 167

Parsing a JSON object in javascript

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!

Upvotes: 2

Views: 439

Answers (2)

Mike Brant
Mike Brant

Reputation: 71384

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)

Upvotes: 2

Mike Park
Mike Park

Reputation: 10931

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.

Upvotes: 10

Related Questions