Reputation: 2763
I have some JSON returned from an HTTP endpoint in the Node.js Request package. The body
of the response is a JSON object with the following (Content-Type
of application/json
) :
{
exchange_rate: 1.0,
format: {
symbol: '$',
precision: 2,
thousands_separator: ',',
decimal_separator: '.'
}
}
When I use console.log(body);
I get the following (it's verbatim to the above):
{
exchange_rate: 1.0,
format: {
symbol: '$',
precision: 2,
thousands_separator: ',',
decimal_separator: '.'
}
}
However, when I try to access the exchange_rate
value, it returns undefined
:
console.log(body.exchange_rate);
I tried to use JSON.parse(body);
however it fails because it's already JSON:
SyntaxError: Unexpected token e
at Object.parse (native)
...
Any idea how I can access the individual properties of this JSON?
Upvotes: 2
Views: 281
Reputation: 943108
Your problem is that what you have is not JSON.
Property names in JSON must be represented by strings, not identifiers. Strings must be quoted using "
characters and not '
.
You are getting the Unexpected token e
error because you have an e
where you should have a "
.
If you had had a JavaScript object (i.e. had successfully parsed the "JSON") you would get Unexpected token o
(o not e) because it would have stringified to [object Object]
.
Upvotes: 4