oderfla
oderfla

Reputation: 1797

Cannot extract key/value from json

A resource is fetched in node.js like this:

requestify.post('myurl')
.then(function (response) {
    console.log(response);
    console.log(response.body);
});

console.log(response) gives:

Response {
    code: 200,
    body: '{"guid":"abcd","nounce":"efgh"}' 
}

console.log(response.body) gives:

{"guid":"abcd","nounce":"efgh"}

However, for some reason I cannot access the key "guid" or "nounce". In both cases I get an undefined. I have tried both with

console.log(response.body.guid);

and

console.log(response.body['guid']);

Upvotes: 1

Views: 388

Answers (3)

Tschallacka
Tschallacka

Reputation: 28722

You need to set the return type to

response.writeHead(200, {"Content-Type": "application/json"});

so your receiving end will make it an object automagically when received. See Responding with a JSON object in NodeJS (converting object/array to JSON string)

Upvotes: 1

kapantzak
kapantzak

Reputation: 11750

It seems that the value of body property is a string. You must parse it as JSON:

console.log(JSON.parse(response.body).guid);

Upvotes: 1

smnbbrv
smnbbrv

Reputation: 24541

The body is string, but you want it to be an object. Just transform it:

JSON.parse(response.body).guid

Upvotes: 1

Related Questions