adventure_galley
adventure_galley

Reputation: 7

Access to properties of JSON in Node JS

I'm trying to access the age but I cannot, how can I do that?

var json = '{"carlos":{"data":{"age":"30","phone":"3226458186"}}}';
var obj = JSON.parse(JSON.stringify(json));

This doesn't work for me, obj.carlos is undefined

console.log("Age of Carlos: ", obj.carlos.data.age);

Upvotes: 0

Views: 1545

Answers (4)

Mitesh Sathavara
Mitesh Sathavara

Reputation: 429

the problem here is the unnecessary call to JSON.parse(JSON.stringify(json)) conver javascript object to JSON like: JSON.parse(json)

example : 

 var json = '{"carlos":{"data":{"age":"30","phone":"3226458186"}}}';
 var obj = JSON.parse(JSON.stringify(json));
 console.log("Phone of Carlos: ", obj.carlos.data.phone);

Upvotes: 2

Muhammad Zeeshan
Muhammad Zeeshan

Reputation: 4748

No need to JSON.stringify. You just only need to parse your values as they are already a JSON string. Here you go:

var json = '{"carlos":{"data":{"age":"30","phone":"3226458186"}}}';
var obj = JSON.parse(json);

console.log("Age: ", obj.carlos.data.age);

Upvotes: 4

Kris
Kris

Reputation: 135

You cannot use JSON.stringify() here, because this method converts a JavaScript object or value to a JSON string and you already got a JSON string. So your code should look like this:

var json = '{"carlos":{"data":{"age":"30","phone":"3226458186"}}}';
var obj = JSON.parse(json);

Upvotes: 1

William Stanley
William Stanley

Reputation: 751

The problem here is the unnecessary call to JSON.stringify, that method is used to convert JavaScript objects to JSON, but has nothing to do with deserializing them.

The code that you need is just this:

var obj = JSON.parse(json);

Upvotes: 4

Related Questions