简体   繁体   中英

unable to get JSON value response

I'm making an API call using node js and I'm getting the below response of type string (knew this when I did typeOf ).

{
    "metadata": {
        "provider": "Press"
    },
    "results": [
        {
            "senses": [
                {
                    "definitions": [
                        "this is an animal"
                    ]
                }
            ]
        }
    ]
}

And from this response I need to pull this is an animal , and I'm trying to get the data using the below code piece.

console.log(JSON.parse(body.results[0].senses[0].definitions[0]));

but this is giving me an error as below

console.log(JSON.parse(body.results[0].senses[0].definitions[0]));
                                   ^

TypeError: Cannot read property '0' of undefined

please let me know where am I going wrong and how can I fix this.

Thanks

You're trying to parse the content of your object, which is not yet a JSON object. You need to parse the whole "body" variable, before trying to access the content of it.

Try this:

body = JSON.parse(body);
console.log(body.results[0].senses[0].definitions[0]);

You can also do everything in only one line, though I don't recommend it since you probably want to use this variable afterwards:

console.log(JSON.parse(body).results[0].senses[0].definitions[0]);

You are treating body as if it were an object (you said it was a string) and then are trying to prase "this is an animal" as if it were JSON (which is isn't).

You need to pass the string to JSON.parse and then read the properties of the results of that.

JSON.parse(body).results[0].senses[0].definitions[0]

Note where the ) is in the corrected expression.

You should actually just parse the body as JSON.parse(body) and get the result property from it:

 var body = `{ "metadata": { "provider": "Press" }, "results": [ { "senses": [ { "definitions": [ "this is an animal" ] } ] } ] }`; console.log(JSON.parse(body).results[0].senses[0].definitions[0]); 

您将字符串视为对象,首先需要解析body

console.log(JSON.parse(body).results[0].senses[0].definitions[0])

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