简体   繁体   中英

Pulling Information from JSON

I have the following JSON string:

var txt= '{“group”: [
    {“family1”: {
            “firstname”:”child1”,
            “secondname”:”chlid2”
    }},
    {“family2”: {
            “firstname”:”child3”,
            “secondname”:”child4”
    }}
]}';

I'm having difficulty pulling out information such as "child1". I'm sure if it is just a syntax problem, or I'm not doing it correctly. I've tried doing this:

alert (group[0].family[0].firstname);

But I'm getting nothing....

I see something wrong, and I'm not sure if you notice it.

“family2”

Those are fancy Unicode quotes. Computers don't do well with those quotes. Replace them with standard ASCII (Latin1) quotes – ie " – and then this should work:

var myobj = JSON.parse(txt);
alert(myobj.group[0].family1.firstName);

Is there a reason you are u sing a JSON string and not just a JSON object?

Assuming you've already parsed the string into a JSON object, you are referencing a family array that does not exist. You have family1 and family2 so family[0] does not exists.

You would need to do this: parsedJson.group[0].family1.firstName

It seems that you have to convert your string to object first. Do that with JSON.parse() function that takes string as argument. and returns JavaScript object frow which you can then pull your info:

var info = JSON.parse( txt );
alert( info.group[0].family1.firstname );

Well, first of all, the string you are using isn't closed. In Javascript, strings have to be on a single line.

Second, I would recommend writing it as a JSON object, rather than as a string. You can convert a string to an object, however.

Anyway, here is an example that shows what you want to do: http://jsfiddle.net/vB9AP/

var txt= {"group": [
{"family1": {
        "firstname":"child1",
        "secondname":"chlid2"
}},
{"family2": {
        "firstname":"child3",
        "secondname":"child4"
    }}
]};

alert( txt.group[0].family1.firstname );

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