简体   繁体   中英

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!

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 .

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM