繁体   English   中英

如何从 PostgreSQL 中的 Json 数组中获取元素

[英]How to get elements from Json array in PostgreSQL

我已经对此进行了很多搜索,但仍然无法回答。 我正在使用 PostgreSQL。 在下面的示例中,列名称是“部分”,列类型是 json[]。

我的专栏在数据库中看起来像这样:

sections
[{"name"      : "section1",
  "attributes": [{"attrkey1": "value1",
                  "attrkey2": "value2"},

                 {"attrkey3": "value3",
                  "attrkey4": "value4"}]
 },
 {"name"      : "section2",
  "attributes": [{"attrkey3": "value5",
                  "attrkey6": "value6"},

                 {"attrkey1": "value7",
                  "attrkey8": "value8"}]
 }]

它是 json 数组,我想在我的结果中得到“attrkey3”。 为了从 Json 获取特定的密钥,我可以使用json_extract_path_text(json_column, 'json_property') ,它工作得非常好。 但我不知道如何从 json[] 获取一些属性。

如果我谈论上面的例子,我想在我的结果中显示属性“attrkey2”的值。 我知道它是一个数组,所以它的工作方式可能与平时不同,例如,我的数组的所有值都将充当不同的行,因此我可能必须编写子查询,但不知道该怎么做。

此外,我无法静态写入索引并从某个特定索引获取 json 元素的属性。 我的查询将动态生成,所以我永远不会知道 json 数组中有多少元素。

我看到了一些静态示例,但不知道如何在我的情况下实现它。 有人可以告诉我如何在查询中做到这一点吗?

我不确定您是否有一个json[] (PostgreSQL json值数组)类型的列,或一个json类型的列,它似乎是一个 JSON 数组(如您的示例中所示)。

无论哪种情况,您都需要在查询之前扩展您的数组。 如果是json[] ,则需要使用unnest(anyarray) 如果是json类型列中的 JSON 数组,则需要使用json_array_elements(json) (和LATERAL连接——它们在我的示例中是隐式的):

select     t.id,
           each_section ->> 'name' section_name,
           each_attribute ->> 'attrkey3' attrkey3
from       t
cross join unnest(array_of_json) each_section
cross join json_array_elements(each_section -> 'attributes') each_attribute
where      (each_attribute -> 'attrkey3') is not null; 
-- use "where each_attribute ? 'attrkey3'" in case of jsonb


select     t.id,
           each_section ->> 'name' section_name,
           each_attribute ->> 'attrkey3' attrkey3
from       t
cross join json_array_elements(json_array) each_section
cross join json_array_elements(each_section -> 'attributes') each_attribute
where      (each_attribute -> 'attrkey3') is not null;

SQLFiddle

不幸的是,您不能对您的数据使用任何索引。 您需要先修复您的架构,才能做到这一点。

而且,如果array有一个键值映射数据:

select each_data -> 'value' as value3 
from t cross join jsonb_array_elements(t.sections -> 'attributes') each_attribute 
where each_attribute -> 'key' = '"attrkey3"'

我之所以提到这一点,是因为出色的答案也为我的案例提供了完美的解决方案。 顺便说一下,还要注意jsonb_array .. jsonb类型属性的方法。

如果您希望访问单个元素,请使用json_array -> [index]

例如,如果您有json_arr=[1,2,3]那么json_array -> 0将返回 1

暂无
暂无

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

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