这是我正在查询的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"]
有人知道如何取消嵌套/将item列中的值扩展到新行吗?谢谢:)
答案 0 :(得分:1)
你非常亲密。
只需使用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)