首页 > 解决方案 > 如何将字符串中的数组解析为javascript数组

问题描述

我从数据库调用中收到了一个字符串,如下所示:

"[{'url':'https://www.example.com/','category':'popular'},{'url':'https://example2.com/','category':'new'}]"

我想将字符串解析为 typescript/JS 数组,使其如下所示:

[
   {'url':'https://www.example.com/','category':'popular'}, 
   {'url':'https://example2.com/','category':'new'}
]

我该怎么做呢?JSON.parse 不起作用,因为字符串不像字符串化的 JSON。谢谢!

标签: javascriptarraysstringtypescript

解决方案


假设其中没有包含 的字符串',您可以将所有出现的单引号替换为双引号,然后您可以解析它:

const str = "[{'url':'https://www.example.com/','category':'popular'},{'url':'https://example2.com/','category':'new'}]";

const arr = JSON.parse(str.replace(/'/g,'"'));

console.log(arr);


推荐阅读