【问题标题】:How to fix the invalid JSON in my case?在我的情况下如何修复无效的 JSON?
【发布时间】:2017-01-28 02:00:18
【问题描述】:

我从 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 作斗争好几个小时了,真的不知道我还能做什么。任何人都可以帮忙吗?非常感谢!

【问题讨论】:

  • 您可能对原始数据进行了两次编码(您共享的代码中现在显示了一些内容)。永远不要使用字符串操作函数来操作标准数据格式。
  • 你确定你没有在 Postgres 中使用json[](又名json数组)类型吗?因为这就是你的输出的样子。

标签: javascript json node.js postgresql


【解决方案1】:

您应该修复保存在数据库中的数据,如 cmets 中建议的那样,数据被多次 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]));
}

【讨论】:

    【解决方案2】:
    newJson = JSON.parse(JSON.stringify(newJson))
    

    试试这个

    【讨论】:

      猜你喜欢
      • 2018-11-29
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多