如何将具有多个对象类结构的字符串转换为 JavaScript 对象

How to convert string which has multiple object like structure into JavaScript object

我需要将下面的 字符串 转换为 JavaScript 对象

const str = `[{"a":"b"},{"c":"d"}]
[{"a":"b"},{"c":"d"}]`

我正在寻找像

这样的对象
[[{"a":"b"},{"c":"d"}],[{"a":"b"},{"c":"d"}]]

我试过下面的代码

const regex = /(\n)/gm;
const str = `[{"a":"b"},{"c":"d"}]
[{"a":"b"},{"c":"d"}]`;
const subst = `,`;

let result = str.replace(regex, subst);
console.log(result);
JSON.parse(result)

低于输出

[{"a":"b"},{"c":"d"}],[{"a":"b"},{"c":"d"}]

JSON.Parse() 给出以下错误

JSON.parse(result)
undefined:1
[{"a":"b"},{"c":"d"}],[{"a":"b"},{"c":"d"}]
                     ^

SyntaxError: Unexpected token , in JSON at position 21
    at JSON.parse (<anonymous>)
    at Object.<anonymous> (C:\regextest.js:11:6)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Function.Module.runMain (module.js:676:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3

要将字符串转换为对象,请使用 JSON.parse 方法:

JSON.parse('{ "name":"John", "age":30, "city":"New York"}')

希望对您有所帮助。

使用 JSON.parse 方法可以转换它,但必须将有效字符串传递给它

var str = '[[{"a":"b"},{"c":"d"}],[{"a":"b"},{"c":"d"}]]';
console.log(str);
var obj = JSON.parse(str);
console.log(obj);

我能够解决这个问题,这是代码

const regex = /(\n)/gm;
const str = `[{"a":"b"},{"c":"d"}]
[{"a":"b"},{"c":"d"}]`;
const subst = `;`

let result = str.replace(regex, subst);

result = result.split(';')
let data = []
result.forEach(item => {
  if (item.length > 0) {
    data.push(JSON.parse(item))
  }
})
console.log(data);

输出

[ [ { a: 'b' }, { c: 'd' } ], [ { a: 'b' }, { c: 'd' } ] ]

const str = `[{"a":"b"},{"c":"d"}]
[{"a":"b"},{"c":"d"}]`
console.log(str.split("\n").map(JSON.parse))