kpg
kpg

Reputation: 7966

Accessing an attribute of a js object

I'm using node-rest-client to fetch data from an api. It all goes well until I get the data back (a js object), then I am unable to access the attributes of the response:

console.log("dataObject:", dataObject);
console.log("dataObject.access_token:", dataObject.access_token);
console.log("dataObject['access_token']:", dataObject['access_token']);

prints this to the log:

15:12:39 worker.1  | dataObject: {"access_token":"uzJB9nG1ZbpsJaFy","token_type":"bearer"}
15:12:39 worker.1  | dataObject.access_token: undefined
15:12:39 worker.1  | dataObject['access_token']: undefined

I don't understand how that is possible!

Upvotes: 0

Views: 62

Answers (2)

Salman
Salman

Reputation: 9447

It seems the data you're getting from the rest client is in string. You can quickly try the following and see if it works.

dataObject = JSON.parse(dataObject);

Had it been an object, then the line

console.log("dataObject.access_token:", dataObject.access_token);

would print

15:12:39 worker.1  | dataObject: [object Object]

However, I would suggest, find out why it is coming as string? check if you are sending Content-Type: application/json; charset=utf-8 header properly from the API.

Edit:

Looks like by default node-rest-client expects application/json;charset=utf-8 (No space after semicolon). Either you could send the header from API like this, or modify options in node-rest-client as explained here

Upvotes: 0

Matt Burland
Matt Burland

Reputation: 45135

It all goes well until I get the data back (a js object)

That's where you went wrong. It's not a javascript object, it's a JSON string. The give away is here:

15:12:39 worker.1  | dataObject: {"access_token":"uzJB9nG1ZbpsJaFy","token_type":"bearer"}

Most (maybe all?) Javascript engines won't put " around property names (they are optional) when you log to console. But a JSON string, being a string, has them.

So you should be able to just do:

dataObject = JSON.parse(dataObject);

And then:

console.log(dataObject.access_token);

You don't show how you actually get the JSON in the first place, but many libraries (for example jQuery) will automatically parse for you.

Upvotes: 1

Related Questions