[英]Query JSON nested array and expand to multiple rows in Postgres table
这是我要查询的 JSON 对象:
const data =
{"fruit":["apple"],"vegetables":["carrot","turnip"],"dairy":["milk","cheese"]}'
这是我想在我的 postgres 表中返回的内容:
category | item
--------------------
fruit | apple
vegetables | carrot
vegetables | apple
dairy | milk
dairy | cheese
这是我迄今为止设法做到的:
SELECT key as category, value as item
FROM json_each_text('${data}')
category | item
--------------------
fruit | ["apple"]
vegetables | ["carrot", "turnip"]
dairy | ["milk", "cheese"]
有人知道如何将项目列中的值取消嵌套/扩展到新行吗? 谢谢 :)
你非常接近。
只需使用json_array_elements_text
从 json 数组中提取项目:
SELECT key as category, json_array_elements_text(value::json) as item
FROM json_each_text('{"fruit":["apple"],"vegetables":["carrot","turnip"],"dairy":["milk","cheese"]}'::json);
category | item
------------+--------
fruit | apple
vegetables | carrot
vegetables | turnip
dairy | milk
dairy | cheese
(5 Zeilen)
如果您在使用其他类型的数组时遇到此问题,请考虑使用UNNEST
:
SELECT UNNEST(ARRAY['foo','bar']);
unnest
--------
foo
bar
(2 Zeilen)
SELECT UNNEST('{"foo","bar"}'::TEXT[]);
unnest
--------
foo
bar
(2 Zeilen)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.