【发布时间】: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