我是初学者,并且不知道如何从JSON获取数据。我有以下JSON结构,
{
"title": "Delicate style of embroidery lawn dress",
"field": [
{
"row1": {
"key": "free_homedelivery",
"value": "yes"
}
},
{
"row2": {
"key": "_price",
"value": "60"
}
},
{
"row3": {
"key": "_regular_price",
"value": "60"
}
},
{
"row4": {
"key": "_stock_status",
"value": "instock"
}
}
]
}
我试过了,但控制台说undefined
for(var i =0 ;i < s.length; i++)
{
console.log('key ' + s.field['row'+i].key);
}
这似乎没有获取值......
Here is the Fiddle
答案 0 :(得分:1)
问题
s
? - 假设s
是您粘贴的json s.field
上,但s.length
已使用field
称为数组,但尝试访问数组内对象的属性作为数组的属性。0
开始,row
名称以row1
var numFields = s.field.length; // Good practice to keep length calculated
for(var i = 0; i < numFields; i++){
console.log('key ' + s.field[i]['row'+(i+1)].key);
}
脚注 - JSON太复杂了,它可以像下面这样简单,
var s = {
"title": "Delicate style of embroidery lawn dress",
"field": [
{
"key": "free_homedelivery",
"value": "yes"
},
{
"key": "_price",
"value": "60"
}
]
};
// Updated loop
var numFields = s.field.length; // Good practice to keep length calculated
for(var i = 0; i < numFields; i++){
console.log('key ' + s.field[i].key);
}
希望这有帮助!
答案 1 :(得分:0)
你在json中的对象有点不同(属性名称是row1,row2等),所以你必须做这样的事情:
var json = {
"title": "Delicate style of embroidery lawn dress",
"field": [{
"row1": {
"key": "free_homedelivery",
"value": "yes"
}
}, {
"row2": {
"key": "_price",
"value": "60"
}
}, {
"row3": {
"key": "_regular_price",
"value": "60"
}
}, {
"row4": {
"key": "_stock_status",
"value": "instock"
}
}]
}
for (i = 0; i < json.field.length ; i++){
var item = json.field[i];
var key = item["row" + (i + 1)].key;
alert(key);
}