-1

I have a JSON returned array like this

    {"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":... } ]

This is returned from a php function and then sent to an Ajax call with

echo json_encode($response['body']);

I am trying to get the key values of "food_name", "total_fat", "calories" etc from the ajax function. My Ajax function is like

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 returns

[{…}]
0: 
alt_measures: null
brand_name: null 
food_name: "broccoli" 
full_nutrients: (124)
calories: 108.78 
cholesterol: 42.88

but I am not able to get the specif value of "food_name" or "calories" etc.

Thanks

saq
  • 67
  • 6
  • your json string is not valid, make sure its valid before positing it here. `JSON.parse(data)` will 100% fail with this json string. – Alen.Toma Feb 15 '19 at 19:45

1 Answers1

0

The error is in this line:

"total_fat":3.47,"

There's a " at the end that breaks the JSON.

You can check your JSON format in https://jsonformatter.curiousconcept.com/.

Also, there's an error in your loop. Try something like:

obj = JSON.parse(data);
$.each(obj.foods, function(i, item) {
   var testname = item.total_fat;
   alert(testname);
});