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

时间:2016-09-20 08:24:20

标签: javascript json node.js postgresql

我有一个无效的json stringify数据从postgres数据库返回。

它是一个无效的字符串,数据就像

{"{\"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打几个小时,真的不知道我还能做些什么。有人可以帮忙吗?非常感谢!

2 个答案:

答案 0 :(得分:1)

您应该像注释中建议的那样修复数据库中保存的数据,数据经过多次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]));
}

答案 1 :(得分:1)

newJson = JSON.parse(JSON.stringify(newJson))

尝试使用此