简体   繁体   English

使用节点中嵌套对象的字符串文字进行 JSON 解析

[英]JSON parse with string literals with nested objects in node

Problem with JSON.parse in nested json object string嵌套 json 对象字符串中 JSON.parse 的问题

I have a author object as:我有一个作者对象:

var a = {"firstName":"abhi", "lastName":"pat"}

Am using the JSON parse with other data as:我将 JSON 解析与其他数据一起使用:

JSON.parse(`{"name": "u", "author": "${a}"}`)

I got the the output as:我得到的输出为:

{name: "u", author: "[object Object]"}

The expected output is:预期的输出是:

{name: "u", author: {firstName: "abhi", lastName: "pat"}}

Can anyone suggest me the right way to parse it?谁能建议我解析它的正确方法?

You need to stringify a , not put it directly into the JSON.您需要对a进行字符串化,而不是将其直接放入 JSON 中。

JSON.parse(`{"name": "u", "author": ${JSON.stringify(a)}}`)

But you shouldn't contruct JSON directly as a string in the first place, you should use JSON.stringify() for the whole thing:但是首先你不应该直接将 JSON 构造为字符串,你应该使用JSON.stringify()来完成整个事情:

JSON.parse(JSON.stringify({name: "u", author: a}))

You can use other methods for object assign:您可以使用其他方法进行对象分配:

var a = {"firstName":"abhi", "lastName":"pat"}
console.log({"name": "u", "author": Object.assign({}, a)});

No need JSON.parse or JSON.stringify methods.不需要JSON.parseJSON.stringify方法。

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

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