user3872094
user3872094

Reputation: 3351

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

Upvotes: 0

Views: 153

Answers (4)

Kenny Alvizuris
Kenny Alvizuris

Reputation: 445

You are treating the string as object, first you need to parse the body:

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

Upvotes: 0

Quentin
Quentin

Reputation: 944011

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.

Upvotes: 1

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

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]);

Upvotes: 0

Reyedy
Reyedy

Reputation: 918

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]);

Upvotes: 1

Related Questions