简体   繁体   中英

Can't access json data

I know this is a simple question, but I can't access the data in my json object. It looks like this:

var string={"data":
[
        {
        "city": "Gansu",
        "value": "#000"
        },
        {
        "city": "Ningzhau",
        "value": "#000"
        },
        {
        "city": "Chongqing",
        "value": "#000"
        }
     ]
 };
 var obj =JSON.parse(string);

To test it, I am doing: document.write(obj.data[0].city); which I think should return Gansu.

Can someone tell me what is wrong with the last line of code and how to fix it? Thanks.

'string' is already an object, no need to convert it.

Just do string.data[0].city;

Or you shouldn't have parsed the JSON:

var string={"data":
[
        {
        "city": "Gansu",
        "value": "#000"
        },
        {
        "city": "Ningzhau",
        "value": "#000"
        },
        {
        "city": "Chongqing",
        "value": "#000"
        }
     ]
 };

alert(string.data[0].city);

You forgot to add quotes around the JSON data, hence it's actually an object. JSON.parse() expects a string. It should look something like this:

var string = '{"data":[{"city": "Gansu","value": "#000"},{"city": "Ningzhau","value": "#000"},{"city": "Chongqing","value": "#000"}]}';
// ----------^-----------------------------------------------------------------------------------------------------------------------^

var obj = JSON.parse(string);
document.write(obj.data[0].city);

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