Javascript 在 nodejs 中解析 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14208707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
parsing JSON in nodejs
提问by Amanda G
Hi i have the below json
嗨,我有以下 json
{id:"12",data:"123556",details:{"name":"alan","age":"12"}}
i used the code below to parse
我使用下面的代码来解析
var chunk={id:"12",data:"123556",details:{"name":"alan","age":"12"}}
var jsonobj = JSON.parse(chunk);
console.log(jsonobj.details);
The output that i received is
我收到的输出是
{"name":"alan","age":"12"}
I need to get the individual strings from details say i should be able to parse and get the value of "name".I am stuck here any help will be much appreciated
我需要从细节中获取单个字符串说我应该能够解析并获取“名称”的值。我被困在这里任何帮助将不胜感激
回答by ma?ek
If you already have an object, you don't need to parse it.
如果您已经有一个对象,则不需要解析它。
var chunk={id:"12",data:"123556",details:{"name":"alan","age":"12"}};
// chunk is already an object!
console.log(chunk.details);
// => {"name":"alan","age":"12"}
console.log(chunk.details.name);
//=> "alan"
You only use JSON.parse()when dealing with an actual json string. For example:
您仅JSON.parse()在处理实际 json 时使用string。例如:
var str = '{"foo": "bar"}';
console.log(str.foo);
//=> undefined
// parse str into an object
var obj = JSON.parse(str);
console.log(obj.foo);
//=> "bar"
See json.orgfor more details
有关更多详细信息,请参阅json.org
回答by Hui Zheng
Since jsonobjhas already been parsed as a JavaScript Object, jsonobj.details.nameshould be what you need.
既然jsonobj已经被解析为 JavaScript Object,jsonobj.details.name应该就是你所需要的。

