在纯Javascript中读取复杂的JSON
我有以下json对象,我想读取它(从中访问一些数据) 我怎样才能用Javascript来做呢在纯Javascript中读取复杂的JSON,javascript,json,Javascript,Json,我有以下json对象,我想读取它(从中访问一些数据) 我怎样才能用Javascript来做呢 var allSites = {"oldSites": [ { "site0" : "http://site0.com/", "site1" : "http://site1.com/", "site2" : "http://site2.com/"
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"
}
]
};
这是我做的,但我没有定义
var allSites = eval(allSites);
alert(allSites.oldSites.site0);
谢谢。使用
allSites.oldSites[0].site0
allSites.oldSites
是一个数组。因此,您必须使用索引进行迭代
allSites.oldSites[0].site0
allSites.oldSites
是一个数组。因此,您必须使用索引进行迭代,如果您的对象是如您所描述的那样定义的,它不是JSON,您不需要使用eval
然后,由于oldSites
是一个数组,因此必须对其进行索引,如oldSites[0]
以获取第一个值
然后,获取所检索对象的site0
键
因此,您应该使用:
allSites.oldSites[0].site0
如果您的对象是如您所述定义的,它不是JSON,您不需要使用eval
然后,由于oldSites
是一个数组,因此必须对其进行索引,如oldSites[0]
以获取第一个值
然后,获取所检索对象的site0
键
因此您应该使用:
所有站点。旧站点[0]。站点0
请删除使旧站点成为数组的方括号
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"
}
};
请删除使旧站点成为阵列的方括号
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"
}
};
它不是JSON对象,因为JSON只是以字符串形式表示JAVASCRIPT文本对象的格式化约定。在不使用
eval
ing对象的情况下执行此操作(无论如何,对于JSON字符串,您应该使用JSON.parse
),请尝试以下操作:警报(allSites.oldSites[0].site0);它不是JSON对象,因为JSON只是以字符串形式表示JAVASCRIPT文本对象的格式化约定。在不使用eval
ing对象的情况下执行此操作(无论如何,对于JSON字符串,您应该使用JSON.parse
),请尝试以下操作:警报(allSites.oldSites[0].site0);如果您同意,请标记其中一个解决方案。如果您同意,请标记其中一个解决方案。我使用此解决方案工作正常,但出于某种原因(编码原因)需要访问site0索引,如下所示:allSites.oldSites[0]
而不是allSites.oldSites.site0
有可能吗?您的评估状态为'allSites.oldSites.site0',因此删除[
]
是一种选择,但它取决于要求:)我使用了此解决方案,效果良好,但出于某种原因(编码原因)要像这样访问site0索引:allSites.oldSites[0]
而不是allSites.oldSites.site0
有可能吗?您的评估状态为“allSites.oldSites.site0”,因此可以选择删除[
]
,但这取决于要求:)