Reputation: 1095
I have the following json object and I would like to read it (access some data from it)
how can I do it in Javascript please ?
var allSites =
{"oldSites":
[
{
"site0" : "http://site0.com/",
"site1" : "http://site1.com/",
"site2" : "http://site2.com/"
}
],
"newSites":
[
{
"site0" : "http://site0/new",
"site1" : "http://site1/new",
"site2" : "http://site2/new"
}
]
};
This is what I did but I get undefined.
var allSites = eval(allSites);
alert(allSites.oldSites.site0);
Thanks.
Upvotes: 0
Views: 64
Reputation: 1655
Please remove the square brackets which make oldSites an array
var allSites =
{"oldSites":
{
"site0" : "http://site0.com/",
"site1" : "http://site1.com/",
"site2" : "http://site2.com/"
}
,
"newSites":
{
"site0" : "http://site0/new",
"site1" : "http://site1/new",
"site2" : "http://site2/new"
}
};
Upvotes: 1
Reputation: 9822
If your object is defined like you have described, it is not JSON, you do not need to use eval
.
Then, since oldSites
is an array, you have to index it, like oldSites[0]
to get the first value.
Then, get the site0
key of the object retrieved.
So you should use: allSites.oldSites[0].site0
Upvotes: 3
Reputation: 133453
Use
allSites.oldSites[0].site0
allSites.oldSites
is an array. So you have to iterate using index
Upvotes: 2