I have a Postgres table that has content similar to this:

id  | data

1   | {"a":"4", "b":"5"}
2   | {"a":"6", "b":"7"}
3   | {"a":"8", "b":"9"}

第一列是整数,第二列是json列.

I want to be able to expand out the keys and values from the json so the result looks like this:

id  | key  | value

1   | a    | 4
1   | b    | 5
2   | a    | 6
2   | b    | 7
3   | a    | 8
3   | b    | 9

Can this be achieved in Postgres SQL?


What I've tried

Given that the original table can be simulated as such:

select *
from 
(
values
(1, '{"a":"4", "b":"5"}'::json),
(2, '{"a":"6", "b":"7"}'::json),
(3, '{"a":"8", "b":"9"}'::json)
) as q (id, data)

我可以通过以下方式获得 keys :

select id, json_object_keys(data::json)
from 
(
values
(1, '{"a":"4", "b":"5"}'::json),
(2, '{"a":"6", "b":"7"}'::json),
(3, '{"a":"8", "b":"9"}'::json)
) as q (id, data)

我可以把它们做成创纪录的唱片,就像这样:

select id, json_each(data::json)
from 
(
values
(1, '{"a":"4", "b":"5"}'::json),
(2, '{"a":"6", "b":"7"}'::json),
(3, '{"a":"8", "b":"9"}'::json)
) as q (id, data)

但我不知道如何用id、key和value实现这个结果.

有什么 idea 吗?

Note: the real json I'm working with is significantly more nested than this, but I think this example represents my underlying problem well.

推荐答案

SELECT q.id, d.key, d.value
FROM q
JOIN json_each_text(q.data) d ON true
ORDER BY 1, 2;

函数json_each_text()是一个集合返回函数,因此您应该将其用作行源.函数的输出在这里是joined laterally到表q,这意味着对于表中的每一行,来自data列的每个(key, value)对仅连接到该行,从而保持了原始行和由json对象形成的行之间的关系.

q也可以是非常复杂的子查询(或者像您的问题中的VALUES子句).在该函数中,将根据该子查询的求值结果使用适当的列,因此您仅使用对子查询的别名和子查询中的(别名)列的引用.

Json相关问答推荐

两种情况下过滤的JOLT规范

JOLT拉平数组

将嵌套的json中的字符串强制转换为数字

Jolt需要将缺少的值设置为空并保持相同的位置

使用动态和可变JSON的图表多条

如何创建可由Gin序列化到json的排序键值映射?

属性错误:';ActivitiesClient';对象没有属性';base_url';

无法访问id的第三级json

在 postgres 14 中将记录转换为所需的 json 格式

GitHub Pages无法正确显示我的项目

Jolt 转换数组对象并将某些字段移动到嵌套数组

shell解析json并循环输出组合变量

现代浏览器一次可以处理多少个 HTML 元素?

如何在golang中获取 struct 的json字段名称?

如何从 mysql 数据库构建 JSON 数组

Android 上的 JSON - 序列化

在浏览器中查看 JSON 文件

通过 JSON 发送 HTML 代码

在播放框架 JsObject 中解析 Json 数组

jq:按属性分组和键