简体   繁体   English

如何将JSON转换为node.js对象

[英]How to convert JSON to node.js object

I have a JSON tree like this that is being posted to my node.js (we'll call it message for the sake of this question): 我有一棵这样的JSON树被发布到我的node.js中(为了这个问题,我们将其称为message):

var message = ["layer1": [
                     "color": "Blue",
                     "size": "small",
                     "layer2": [
                         "item1": "TEST"
                     ]
                  ]
              ]

How can I make it so I can access individual nodes and values in node.js, something like this: 如何做到这一点,以便可以访问node.js中的各个节点和值,如下所示:

var sample1 = message.layer1
var sample2 = message.layer1.layer2.item1

if I were to console.log(sample1) it would look like this: 如果我要使用console.log(sample1) ,它将如下所示:

["color": "Blue",
 "size": "small",
 "layer2": [
     "item1": "TEST"
     ]
]

and console.log(sample2) would look like this: console.log(sample2)看起来像这样:

"TEST"

Is this possible? 这可能吗?

The syntax of your message variable is not Javascript (your message seems to be an array, but have key:value , which is not allowed in Javascript). 您的message变量的语法不是Javascript(您的message似乎是一个数组,但是具有key:value ,这在Javascript中是不允许的)。

You have to replace " [ " by " { " and " ] " by " } " in your message to have a Javascript object. 您必须在message中将“ [ ”替换为“ { ”,将“ ] ”替换为“ } ”,才能使用Javascript对象。 Then your sample1 and sample2 variables should work. 然后您的sample1sample2变量应该起作用。

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

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