javascript - 如何将字符串中的数组解析为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。谢谢!
解决方案
假设其中没有包含 的字符串'
,您可以将所有出现的单引号替换为双引号,然后您可以解析它:
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);
推荐阅读
- php - POST选中和未选中复选框状态(PHP)
- python - 如何在 PyQt5,python 中使用按键事件更改图像
- javascript - 如何以干净的方式回显列表的几个名称
- azure - 如何从浏览器连接到 Azure Redis 缓存?
- java - 在 jupyter-notebook 但不在控制台中运行时,extract_tables 函数出错
- amazon-web-services - OPSWorks 堆栈 - 不会创建
- c# - 使用泛型时省略类型的正确方法是什么?
- python - 如何逐行将字符串写入文件python
- algorithm - 将偏移分页转换为页码分页的算法
- python - 如何翻转 seaborn 的 sns.heatmap 的颜色缩放?