0

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.

4

3 回答 3

1

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

Just do string.data[0].city;

于 2013-08-09T02:42:45.173 回答
1

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);
于 2013-08-09T02:42:53.240 回答
0

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);
于 2013-08-09T02:42:00.883 回答