简体   繁体   English

使用嵌套从 JSON 中提取值

[英]Extract values from JSON with nesting

I have a problem with taking all values under the "id_ref_directory" keys.我在获取“id_ref_directory”键下的所有值时遇到问题。

I have a temp table:我有一个临时表:

CREATE LOCAL TEMP TABLE parsed_json(
    var_key text, 
    var_value text NOT NULL)
ON COMMIT DROP;

I have a JSON, in temp table:我有一个 JSON,在临时表中:

INSERT INTO parsed_json(var_key, var_value)
SELECT * 
FROM json_each_text(var_in_json::json)
WHERE value IS NOT NULL and LENGTH(value) != 0;

I have var int[]:我有 var int[]:

var_territory_list := (SELECT var_value FROM parsed_json WHERE var_key = 'territory_custom');

And I have JSON like this in "value" field:我在“值”字段中有这样的 JSON:

[{"name_directory": "ЯПОНИЯ", "id_ref_directory": 38},
{"name_directory": "ЯПОН", "id_ref_directory": 39}, 
{"name_directory": "ЯП", "id_ref_directory": 40}]}

I need to write into var_territory_list this from JSON abowe (values of keys "id_ref_directory"):我需要写入var_territory_list从JSON这个abowe(键的值“id_ref_directory”):

[38, 39, 40]

I thought that I could solve everything with simple operators like #> but I failed.我以为我可以用#>类的简单运算符解决所有问题,但我失败了。 Maybe it is necessary to do it through a cycle?也许有必要通过一个循环来做? Thank you in advance!先感谢您!

Click: step-by-step demo:db<>fiddle 点击:分步演示:db<>fiddle

SELECT
    jsonb_agg(elems -> 'id_ref_directory')
FROM mytable,
    jsonb_array_elements(mydata -> 'territory_custom') AS elems
  1. jsonb_array_elements() gives you one row per array element jsonb_array_elements()为每个数组元素提供一行
  2. elems -> 'id_ref_directory' gives you the expected values of these elements elems -> 'id_ref_directory'为您提供这些元素的预期值
  3. jsonb_agg() aggregates them into a JSON array jsonb_agg()将它们聚合成一个 JSON 数组

If you want an int array:如果你想要一个int数组:

SELECT
    array_agg((elems ->> 'id_ref_directory')::int)
FROM mytable,
    jsonb_array_elements(mydata -> 'territory_custom') AS elems
  1. Instead of jsonb_agg() use array_agg() after casting the elements into int values在将元素转换为int值后,使用array_agg()代替jsonb_agg()

Postgres 12 allows to use JSONpath: Postgres 12允许使用 JSONpath:

Click: demo:db<>fiddle 点击:demo:db<>fiddle

SELECT
    jsonb_path_query_array(mydata, '$.territory_custom.id_ref_directory') elems
FROM mytable
  1. '$.territory_custom.id_ref_directory' gives you all expected elements '$.territory_custom.id_ref_directory'为您提供所有预期元素
  2. The function aggregates the result into an array该函数将结果聚合到一个数组中

If you want an int array:如果你想要一个int数组:

SELECT
    array_agg(elems::int)
FROM mytable,
    jsonb_path_query(mydata, '$.territory_custom.id_ref_directory') elems
  1. Calculate all elements into one row per element每个元素将所有元素计算为一行
  2. Aggregate these elements with array_agg() after casting them into int values将这些元素转换为int值后,使用array_agg()聚合这些元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM