Home > Back-end >  How to make a fetch variable JSON readable and then parse values
How to make a fetch variable JSON readable and then parse values

Time:08-12

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.

CodePudding user response:

    .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())
  • Related