简体   繁体   English

JSON.parse:解析对象中的数组

[英]JSON.parse: parse array in object

I have a JSON string of an object that has an array as one of its properties.我有一个对象的 JSON 字符串,该对象具有一个数组作为其属性之一。 How can I get the resulting object to have an array of strings:如何让结果对象具有字符串数组:

 let arr = ['10','22']; let obj = `{ "name":"bob", "arr":"${arr}" }`; let parse = JSON.parse(obj); console.log(parse);

Expected Output:预期输出:

{
    "name":"bob",
    "arr":['10','22']
}

You should use JSON.stringify and remove two double-quotes "您应该使用JSON.stringify并删除两个双引号"

 let arr = ["10", "22"] let obj = `{ "name":"bob", "arr":${JSON.stringify(arr)} }` let parse = JSON.parse(obj) console.log(parse)

The problem is in the definition.问题出在定义上。 You are trying to include an array in the string.您正在尝试在字符串中包含一个数组。 And if you try to print array as a string in JavaScript it joins the keys with , .如果您尝试在 JavaScript 中将数组打印为字符串,它会将键与,连接起来。 To make it work, you need to convert the array as JSON string and remove the double-quotes, and it will work as expected.要使其工作,您需要将数组转换为 JSON 字符串并删除双引号,它将按预期工作。

let arr = ['10','22'];
let obj = `{
    "name":"bob",
    "arr": ${JSON.stringify(arr)}
}`;
let parse = JSON.parse(obj);
console.log(parse);

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

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