首页 > 解决方案 > 如何从json转换字符串?

问题描述

我正在研究由 MongoDB 提供支持的 postgresql 基础。摄入量全部采用 JSON 格式,碰巧某些字段以 STRING 形式出现,我无法检索该值。

例如,字段和值如下:

"Info":
"{\" categoryName \ ": \" Sale \ ", \" seller \ ": \" Uber \ ", \" categoryId \ ": \" 022 \ ", \" Payment \ ": false}"

已经尝试使用 REPLACE、SPLIT_PART、CONVERTER STRING PRA JSON,但没有任何效果。

SELECT case 
    when json->'payload'->'com'->0->>'Info' is null 
    then '' 
    else json->'payload'->'com'->0->>'Info'::json 
end Test
FROM tableJson

我需要将此行转换为 JSON:

"Info": {
"categoryName": "Sale",
"seller": "Uber",
"categoryId": "022",
"Payment": false "}

标签: jsonpostgresql

解决方案


您需要进行一些正则表达式替换以删除所有反斜杠,然后使用大括号格式化外部节点{}

postgres=# select cast('{"Info":
{"categoryName": "Sale", "seller": "Uber", "categoryId": "022", "Payment": false}}' as json);
                                        json                                        
------------------------------------------------------------------------------------
 {"Info":                                                                          +
 {"categoryName": "Sale", "seller": "Uber", "categoryId": "022", "Payment": false}}
(1 row)

推荐阅读