Reputation: 260
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....
Upvotes: 1
Views: 83
Reputation: 567
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 );
Upvotes: 0
Reputation: 3167
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
Upvotes: 0
Reputation: 2014
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 );
Upvotes: 0
Reputation: 30595
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 – i.e. "
– and then this should work:
var myobj = JSON.parse(txt);
alert(myobj.group[0].family1.firstName);
Upvotes: 3