javascript - 如何修复我的情况下的无效 JSON?

标签 javascript json node.js postgresql

我从 postgres 数据库返回了无效的 json stringify 数据。

这是一个无效的字符串,数据如下

{"{\"title\":\"john\"}","{\"tel\":\"12345\"}"}

在我的代码中,我使用以下代码使其有效:

var newJson = '"' + mydata.info.replace(/","/g, ",").replace(/^{"/, "[").replace(/"}$/, "]") + '"';

但是,当我执行 JSON.parse(newJson) 时,它仍然给我字符串而不是对象。

替换方法后的 newJson 值如下所示

console.log(newJson) =>  "["{\"title\":\"john\"},{\"tel\":\"12345\"}"]"

有趣的是,如果我直接指定它,例如:

newJson =  "["{\"title\":\"john\"},{\"tel\":\"12345\"}"]"
newJson = JSON.parse(newJson)

console.log(typeof newJson) => object

它实际上给了我一个对象。

我已经尝试对抗这个无效的 json 好几个小时了,真的不知道我还能做什么。有人可以帮忙吗?非常感谢!

最佳答案

您应该按照注释中的建议修复保存在数据库中的数据,数据经过多次 json 编码。

如果这确实不可能,你可以尝试用这样的东西来阅读它(未经测试):

// First replace the first and last {} with []
var arrStr = '[' + json.substring(1, json.length - 1) + ']';
// Parse it as an array of strings
var arr = JSON.parse(arrStr);
// Cycle every item in the array and parse it
var results = [];
for (var i = 0; i < arr.length; i++) {
    results.push(JSON.parse(arr[i]));
}

关于javascript - 如何修复我的情况下的无效 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39589100/

相关文章:

node.js - Node Express 响应 Cookie 值已编码

mysql - 如何使用nodejs将本地sql文件转换为json

javascript - 使用 Node js 和 fs 列出目录、子目录及其文件

node.js - 强制 Sequelize 在 Express 路由中更新 req.user

javascript - 根据输入文本按元素排序,AngularJS

javascript - 将对象数组中具有相同对象属性的 JavaScript 对象属性值相加

php - MySQL 选择 IF INNER JOIN

javascript - Firefox 中的 JSON.parse 是否存在错误?

javascript - Angular 2 - 如何使用其他组件作为服务并获取其数据

javascript - 我如何制作页面,每个页面包含 10 个帖子?