Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make a fetch variable JSON readable and then parse values

I am using the nutritionix API for a project and I need to get the value that is returned as result. Below is the relevant portion of the code, and the function section inside is an async function.

let result = fetch("https://trackapi.nutritionix.com/v2/natural/nutrients", requestOptions)
        .then(response => response.text())
        .then(result => {return JSON.parse(JSON.stringify(result));})
        .catch(error => console.log('error: ', error))
    
    console.log(await result)
    console.log('foods: ', await result.foods)
    

The result when console logged is something along the lines of.

{
    "foods": [
        {
            "food_name": "rice cake",
            "brand_name": null,
            "serving_qty": 1,
            "serving_unit": "cake",
            "serving_weight_grams": 9,
            "nf_calories": 34.83,
            ...

So I am trying to make a JSON string so that I can go through and read calories for each food that is listed in foods. But when I read result.foods it comes back as undefined.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

    .then(response => response.text())
    .then(result => {return JSON.parse(JSON.stringify(result));})
  1. result is a string (text)
  2. JSON.stringify converts that to a string containing JSON representation of that string
  3. JSON.parse (the opposite of JSON.stringify) converts that back to the original string

You therefore have a string, which doesn’t have a foods property.


If you were (and you shouldn’t) to use this general approach, you should not stringify the data first.

.then(response => response.text())
.then(result => {return JSON.parse(result);})

That’s a poor choice however since response objects have built-in support for parsing JSON:

.then(response => response.json())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading