简体   繁体   English

将字符串转换为 object 的数组

[英]Convert string to array of object

How to convert a string into an array of the object?如何将字符串转换为 object 的数组?

 let str  = `<%-found%>`;
                    let result = [];
                    JSON.parse(`["${str}"]`.replace(/},{/g, `}","{`)).forEach((e) => {
                        result.push(JSON.parse(e.replace(/{/g, `{"`).replace(/:/g, `":`).replace(/,/g, `,"`)));
});

`<%-found%>` = "{SPOT:0,0:10,1:0},{SPOT:1,0:5,1:5}" 

show this error:显示此错误:

Uncaught SyntaxError: Unexpected token in JSON at position 3 at JSON.parse () at (index):2010未捕获的语法错误:在 JSON.parse () at (index):2010

That's a messed up JSON string you have there.那是你那里的 JSON 字符串搞砸了。 But it seems like your code is already working when I remove that strange reassignment you have at the beginning.但是,当我删除您一开始的奇怪重新分配时,您的代码似乎已经开始工作了。

 let str = "{SPOT:0,0:10,1:0},{SPOT:1,0:5,1:5}"; let result = []; JSON.parse(`["${str}"]`.replace(/},{/g, `}","{`)).forEach((e) => { result.push(JSON.parse(e.replace(/{/g, `{"`).replace(/:/g, `":`).replace(/,/g, `,"`))); }); console.log(result);

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

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