在我的案例中,如何修复无效的JSON

How to fix the invalid JSON in my case?

本文关键字:何修复 无效 JSON 我的 案例      更新时间:2023-09-26

我有一个无效的json字符串数据从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斗争了好几个小时,真的不知道我还能做什么。有人能帮忙吗?非常感谢!

您应该像注释中建议的那样修复保存在DB中的数据,数据是多次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]));
}
newJson = JSON.parse(JSON.stringify(newJson))

尝试使用此