如何从getRequest获取JSON

时间:2014-01-06 19:32:11

标签: javascript json

嗨我的表格中有一个字符串:

{"Fruit":"Meat",
     "Vegetable":[
       {"Name":"Author1","Date":"12"},
       {"Name":"Author2","Date":"2"},
       {"Name":"Author3","Date":"14"}
       .
       .
       .
       {"Name": "AuthorN", "Date":"18"}
    ]
} 

与JSON / GetNames服务相关联。

什么是JavaScript函数可以解析并返回“Vegetable”下的每个“Name”?

2 个答案:

答案 0 :(得分:2)

有了这个:

var jsonStr = '{"Fruit":"Meat","Vegetable":[{"Name":"Author1","Date":"12"},{"Name":"Author2","Date":"2"},{"Name":"Author3","Date":"14"}...{"Name": "AuthorN", "Date":"18"}]}';    
var object = JSON.parse(jsonStr),
    names = [];

for (var i = 0; i < object.Vegetable.length; i++) {
    var item = object.Vegetable[i],
        name = item.Name;
    names.push(name);
}
//Finally print the result:
console.log(names);

或者如果您只想打印名称(更短):

var object = JSON.parse(jsonStr);
for (var i = 0; i < object.Vegetable.length; i++)
    console.log(object.Vegetable[i].Name);

干杯

答案 1 :(得分:1)

Ehh for循环通常有效(一旦数据被解析)。

for (var i = 0; i < data.vegetable.length; i++) {
    console.log(data.vegetable[i].name);
}