我有一个像这样的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,"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函数返回的,然后使用
发送到Ajax调用echo json_encode($response['body']);
我正在尝试从ajax函数获取“ food_name”,“ total_fat”,“ calories”等键值。我的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
但是我无法获得“ food_name”或“卡路里”等的指定值。
谢谢
答案 0 :(得分:-1)
此行中的错误:
"total_fat":3.47,"
结尾处有一个“”,它破坏了JSON。
您可以检查https://jsonformatter.curiousconcept.com/中的JSON格式。
此外,您的循环中有一个错误。尝试类似的东西:
obj = JSON.parse(data);
$.each(obj.foods, function(i, item) {
var testname = item.total_fat;
alert(testname);
});