查询JSON嵌套数组并扩展到Postgres表中的多行

时间:2019-05-03 06:10:35

标签: json postgresql

这是我正在查询的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列中的值扩展到新行吗?谢谢:)

1 个答案:

答案 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)