【发布时间】:2019-07-10 13:04:58
【问题描述】:
我的一个 Postgres 表中有以下文本作为 TEXT 数据类型:
[
{"type": "text", "values": ["General"], "valueType": "string", "fieldType": "text", "value": ["General"], "customFieldId": "ee", "name": "customer_group"},
{"type": "text", "values": ["Vienna"], "valueType": "string", "fieldType": "text", "value": ["Vienna"], "customFieldId": "eU", "name": "customer_city"},
{"type": "text", "values": ["Mario"], "valueType": "string", "fieldType": "text", "value": ["Mario"], "customFieldId": "eZ", "name": "first_name"},
{"type": "text", "values": ["2019-06-30"], "valueType": "date", "fieldType": "text", "value": ["2019-06-30"], "customFieldId": "ea", "name": "created_at_date"}
]
我需要将此 TEXT 字段的值拆分为列和行。为此,我已将 TEXT 列转换为 JSON,如下所示:
SELECT CAST( "customFieldValues" as JSON) "customFieldValues" FROM fr.contacts
但是当我试图操纵这个 JSON 值时,结果是 NULL。
WITH CTE AS(SELECT CAST( "customFieldValues" as JSON) "customFieldValues" FROM fr.contacts
)
SELECT
"customFieldValues" ->>'customer_city' as dd
FROM CTE
有人对此有什么建议吗?如何获取列名及其行中的值。我想根据这些数据创建一个 TABLE。
任何建议都会有很大帮助。
下面是预期的结果,
customer_group customer_city first_name created_at_date
General Vienna Mario 2019-06-30
【问题讨论】:
-
没有“sending_status_update”这样的元素。当然这给出了NULL。请告诉我们预期的结果。
-
@S-Man 非常感谢您的快速回复!我已经将代码编辑为正确的元素(我在这里只复制了一部分代码,并且原始代码中存在列sending_status_update),但即使我给出现有代码,它也显示为NULL。将发布示例结果集。
-
...您将查询代码更改为 customer_city。但在你的例子中,这个元素也不存在......请更精确地工作。
-
@S-Man 我上面提到的示例 JSON 字符串的第二行包含 customer_city ,这是列名,值为 ""............{" type": "text", "values": ["Vienna"], "valueType": "string", "fieldType": "text", "value": ["Spaichingen"], "customFieldId": "eU" , "name": "customer_city"},
-
@S-Man "name": "customer_city", 那是存在的吧?或者如果我错了你能纠正我吗?
标签: json postgresql