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,634
  • 8
  • 45
  • 58
mormaii2
  • 67
  • 1
  • 1
  • 9

2 Answers2

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.

Mike Park
  • 10,845
  • 2
  • 34
  • 50
  • 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! – mormaii2 Oct 24 '12 at 19:49
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)

Mike Brant
  • 70,514
  • 10
  • 99
  • 103