[英]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
jsonb_array_elements()
gives you one row per array element jsonb_array_elements()
为每个数组元素提供一行elems -> 'id_ref_directory'
gives you the expected values of these elements elems -> 'id_ref_directory'
为您提供这些元素的预期值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
jsonb_agg()
use array_agg()
after casting the elements into int
valuesint
值后,使用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
'$.territory_custom.id_ref_directory'
gives you all expected elements '$.territory_custom.id_ref_directory'
为您提供所有预期元素If you want an int
array:如果你想要一个
int
数组:
SELECT
array_agg(elems::int)
FROM mytable,
jsonb_path_query(mydata, '$.territory_custom.id_ref_directory') elems
array_agg()
after casting them into int
valuesint
值后,使用array_agg()
聚合这些元素
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.