我尝试从JSON关联数组调用值。我发现了一些困难,因为我的对象被包装在“”中。例如:
var scifi = [
{
"Show":"TNG",
"Ship":"Enterprise",
"Captain":"Picard"
},
{
"Show":"BSG",
"Ship":"Galactica",
"Captain":"Adama"
},
{
"Show":"Firefly",
"Ship":"Serenity",
"Captain":"Reynolds"
}
]例如,在我假设要调用Adama之前,我会使用以下命令
scifi.Captain[1]然而,这似乎是彻底失败的。任何建议都是值得感谢的。
编辑
我想部分问题可能出在我使用的ajax上。
$.ajax({
url: './php/scifishows.php',
type: 'POST',
//dataType: 'json',
data:
{
show: fav_show
},
success: function(output)
{
alert(output[1].Captain);
}
});这是产生括号的php代码,它循环遍历mysql结果,并将它们放在一个对象中。这当然是由上面的ajax调用的。
$all = array();
while( ($row = mysql_fetch_assoc($result)) ) {
$all[] = $row;
}发布于 2013-06-14 14:03:05
[]表示JSON中的数组,{}表示对象。
因此,至少在您的示例中,因为它的形式是[{},{},...],所以您必须首先通过数组访问,然后才是对象。
// something like
var foo = scifi[1].Captain;注意,你得到的是而不是一个关联数组(至少在Javascript中“关联数组”的定义是这样的)。
要拥有类似于关联数组的东西,您仍然需要使用对象:
var scifi = {
TNG : {
Ship : 'Enterprise',
Captain : 'Picard'
},
BSG : {
Ship : 'Galactica',
Captain : 'Adama'
},
Firefly : {
Ship : 'Serenity',
Captain : 'Reynolds'
}
};然后你就可以像这样访问了:
var foo = scifi.TNG.Captain; // Picard
var bar = scifi.BSG.Ship; // Galactica如果你真的必须使用你拥有的格式,但又想使用我给出的格式,那么你可以直接转换你的原始数据:
var new_scifi = {};
$.each(scifi, function (i,v) {
new_scifi[v.Show] = {
Ship = v.Ship,
Captain = v.Captain
};
});
console.log(new_scifi.Firefly.Captain); // Reynoldshttps://stackoverflow.com/questions/17101962
复制相似问题