最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Access to properties of JSON in Node JS - Stack Overflow

programmeradmin3浏览0评论

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

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);
Share Improve this question edited Feb 25, 2020 at 20:47 kgangadhar 5,0885 gold badges38 silver badges58 bronze badges asked Feb 25, 2020 at 20:43 adventure_galleyadventure_galley 73 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

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);
发布评论

评论列表(0)

  1. 暂无评论