jQuery从JSON返回的数组中获取特定的键值
我有一个类似这样的JSON返回数组jQuery从JSON返回的数组中获取特定的键值,jquery,arrays,json,Jquery,Arrays,Json,我有一个类似这样的JSON返回数组 {"foods":[ {"food_name":"broccoli", "brand_name":null, "serving_qty":1, "serving_unit":"serving", "serving_weight_grams":77.5, "calories":108.78, "total_fat":3.47, "full_nutrients":[{"attr_id":203
{"foods":[
{"food_name":"broccoli",
"brand_name":null,
"serving_qty":1,
"serving_unit":"serving",
"serving_weight_grams":77.5,
"calories":108.78,
"total_fat":3.47,
"full_nutrients":[{"attr_id":203,"value":15.5284},
{"attr_id":204,"value":3.4695},
{"attr_id":205,"value":4.1815},
{"attr_id":207,"value":2.6566},
{"attr_id":208,"value":108.775}.
{"attr_id":... } ]
这是从php函数返回的,然后发送到带有
echo json_encode($response['body']);
我试图从ajax函数中获取“食物名称”、“总脂肪”、“卡路里”等关键值。我的Ajax函数如下
success: function(data) {
alert(data);
$.each(JSON.parse(data), function (i, item) {
//console.log(item);
var testname = item.foods.total_fat,
alert(testname);
);
console.log
返回
[{…}]
0:
alt_measures: null
brand_name: null
food_name: "broccoli"
full_nutrients: (124)
calories: 108.78
cholesterol: 42.88
但我无法获得“食物名称”或“卡路里”等的具体值
谢谢错误在这一行:
"total_fat":3.47,"
最后有一个“符号”打破了JSON
您可以在中检查JSON格式
此外,循环中有错误。请尝试以下操作:
obj = JSON.parse(data);
$.each(obj.foods, function(i, item) {
var testname = item.total_fat;
alert(testname);
});
这是输入错误。我已经更正了。是的,就是这样,我假设console.log是正确的,结果是不正确的,谢谢。您的json字符串无效,请在将其放在此处之前确保其有效。
json.parse(data)
将使用此json字符串100%失败。