Javascript unable to read numbers value

I pulled a set of data from [Build, Collaborate & Integrate APIs | SwaggerHub](Food data central API) which returns in strings and numbers.
The following javascripts works fine when the data was reading a string of text.

// Parse the JSON string
const jsonString = p1;
const javascriptObject = JSON.parse(jsonString);

// Access the "title" property of the object using the provided key
const title = javascriptObject.foods[p2]?.foodNutrients[p2]?.nutrientName;
// Return the title, or a default value if it is not found
return title || "Invalid";

But when it comes to reading amount, it was unable to return the value.
Here’s is the API results.

"foods": [
    {
      "fdcId": 45001529,
      "dataType": "Branded",
      "description": "BROCCOLI",
      "foodCode": "string",
      "foodNutrients": [
        {
          "number": 303,
          "name": "Iron, Fe",
          "amount": 0.53,
          "unitName": "mg",
          "derivationCode": "LCCD",
          "derivationDescription": "Calculated from a daily value percentage per serving size measure"
        }
      ],

I tried to ParseFloat but it didn’t work out. Any coders here?

Works for me :man_shrugging:

const json = JSON.parse(p1);
return json.foods[0].foodNutrients[0].number;
const json = JSON.parse(p1);
return json.foods[0].foodNutrients[0].amount;
1 Like

The results was a lot longer, i tried with the above snippets of code i provided and got it to display the amount. But the picture below is reading from the full results, it gives a blank without an error…

I may be calling the wrong item. instead of amount, i should call the value item.
Anyhow, its working as I hope it will be, the 0 value returns Invalid but I implement the if statement to output the 0 value. Below is the code.

// Parse the JSON string
const jsonString = p1;
const javascriptObject = JSON.parse(jsonString);

// Access the "title" property of the object using the provided key
const title = javascriptObject.foods[p2]?.foodNutrients[p2]?.value;
if (title === 0) {
  return title.toString();
} else {
  return title || "Invalid";
}

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.