JavaScript 将字符串"{7: {type: 'line'}}"转换为对象



如何转换字符串

"{7: {type: 'line'},8: {type: 'line'}}" 

到 JavasScript 对象

{7: {type: 'line'},8: {type: 'line'}}

使用 JSON.parse

JSON.parse(STRING) // convert to object
JSON.stringify(STRING) // convert object to string, that can be used in JSON.parse

不要使用数字作为键,因为不好的做法是你不能访问这样的对象:

var a = {"8": "value"};
// Invalid syntax
console.log(a.8)
// work
console.log(a["8"], a[8]);
var b = {"eight" : "value"};
// work
console.log(b.eight);

最新更新