简体   繁体   English

无法在Node.js中解析JSON

[英]Trouble parsing JSON in Node.js

I am trying to parse JSON that looks like this: 我正在尝试解析如下所示的JSON:

{ "values" : [{ "alpha":8 },{ "beta":4 },{ "gamma":-3 } ]}

I'm parsing it with: console.log(msg.values.alpha) , and get: 我用以下命令进行解析: console.log(msg.values.alpha) ,并获得:

Missing error handler on `socket`.
TypeError: Cannot read property 'alpha' of undefined

This is how I have seen done it on other sites. 这就是我在其他网站上看到的方法。 Doing it with console.log(msg.values) returns undefined , and just running console.log(msg) returns proper JSON . 使用console.log(msg.values)执行此操作会返回undefined ,而仅运行console.log(msg)会返回正确的JSON I have seen other people with this issue, but nothing that is said to do is working. 我见过其他人遇到此问题,但据说没有任何效果。 Thanks! 谢谢!

Don't forget to parse it to an object using JSON.parse 不要忘记使用JSON.parse将其解析为对象

msg.values is an array. msg.values是一个数组。 Technically you would have to access it via msg.values[0].alpha. 从技术上讲,您必须通过msg.values[0].alpha.访问它msg.values[0].alpha.

Better solution. 更好的解决方案。

if you are using underscore npm install underscore 如果您使用下划线npm install underscore

var _ = require('underscore');
var msg = JSON.parse('{ "values" : [{ "alpha":8 },{ "beta":4 },{ "gamma":-3 } ]}');
var alpha = _.find(msg.values, function (value) {
    return value.hasOwnProperty('alpha');
}).alpha;

The underscore solution would allow you to not rely on the order of the array so its probably better style. 下划线解决方案将使您不必依赖数组的顺序,因此它可能是更好的样式。


Here is a fiddle of my code running in a browser. 是我在浏览器中运行的代码的小提琴。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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