简体   繁体   中英

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

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM