简体   繁体   中英

Extracting data from JSON with Node.js

I'm extracting data from a food recipe api and the response is JSON.

{
    "results": [
            {
                "id": 147605,
                "title": "Mac and Cheese",
                "image": "https://spoonacular.com/recipeImages/147605-312x231.png",
                "imageType": "png"
             },
             {
                "id": 137592,
                "title": "Mac and Cheese",
                "image": "https://spoonacular.com/recipeImages/137592-312x231.png",
                "imageType": "png"
             },
             {
                "id": 760335,
                "title": "Mac and Cheese",
                "image": "https://spoonacular.com/recipeImages/760335-312x231.jpg",
                "imageType": "jpg"
             },
             {
                "id": 1047165,
                "title": "Mac and Cheese",
                "image": "https://spoonacular.com/recipeImages/1047165-312x231.jpg",
                "imageType": "jpg"
             }
         ],
         "offset": 0,
         "number": 4,
         "totalResults": 1171
}

I want to extract the title, id, and image. I did:

request(url, (error, response) => {
    console.log(response.body.results["id"])
    console.log(response.body.results["title"])
    console.log(response.body.results["image"])
})

I will want to store them in variables and do other stuff with it, but for now I just want to print it out to the terminal.

I'm getting undefined for all the logs. I'm not sure if I should be doing some sort of loop, or something of that nature.

I should also add, when I do:

    console.log(response.body.results) // outputs undefined
    console.log(response.body)         // outputs the JSON response

So this must mean I'm accessing the results array incorrectly.

Thanks for the help!

When you call:

response.body.results["id"]

You're saying that results is a object when its not an object but instead an array of objects. That being said if you want to access the first object you will have to call it like

console.log(response.body.results[0].id);

and you can put that in a loop if you're trying to get all of them

for (let i = 0; i < response.body.results.length; i++) {
    console.log(response.body.results[i].id)
}

Edit:

One thing I failed to see is that response.body.results returns undefined. as @Carlo Corradini said JSON.parse(response.body) might solve that issue.

An example would be:

let jsonData = JSON.parse(response.body);
console.log(jsonData.results[0].id);

Hopefully this helps. sorry if this got confusing. if so just ask any question you have

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM