对象字符串数组仅转换为对象数组javascript

时间:2019-07-05 08:27:25

标签: javascript arrays object

我有一个包含对象'[{letter: a, number: 1}, {letter: b, number: 2}]'数组的字符串,我正在尝试使用JSON.parse()使它从字面上变成对象数组,但出现错误提示

`SyntaxError: Unexpected token l in JSON at position 2`

我的代码

let a = '[{letter: \'a\', number: 1}, {letter: \'b\', number: 2}]'

let b = JSON.parse(a)

console.log(b)

我什至不能使用a.split(','),因为对象内部有,

我的预期输出是

[{letter: 'a', number: 1}, {letter: 'b', number: 2}]

我该如何解决?

1 个答案:

答案 0 :(得分:3)

在JSON中,密钥必须是字符串,因此您必须像这样重新格式化JSON字符串:

[{"letter": "a", "number": 1}, {"letter": "b", number: 2}]

更多信息,请参见this article