简体   繁体   English

如何从 json 对象数组中获取 select 单个字段?

[英]How to select single field from array of json objects?

I have a JSONB column with values in following JSON structure我有一个 JSONB 列,其值位于 JSON 结构中

{
  "a": "value1", "b": [{"b1": "value2", "b3": "value4"}, {"b1": "value5", "b3": "value6"}]
}

I need to select only b1 field in the result.我只需要 select 结果中的b1字段。 So expected result would be所以预期的结果是

["value2", "value5"]

I can select complete array using query我可以使用查询 select 完整数组

select columnname->>'b' from tablename

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

SELECT
    jsonb_agg(elements -> 'b1')                       -- 2
FROM mytable,
    jsonb_array_elements(mydata -> 'b') as elements   -- 1
  1. a) get the JSON array from the b element (b) extract the array elements into one row each a) 从 b 元素中获取 JSON 数组 (b) 将数组元素分别提取到一行中
  2. a) get the b1 values from the array elements (b) reaggregate these values into a new JSON array a) 从数组元素中获取 b1 值 (b) 将这些值重新聚合到新的 JSON 数组中

If you are using Postgres 12 or later, you an use a JSON path query:如果您使用的是 Postgres 12 或更高版本,则可以使用 JSON 路径查询:

select jsonb_path_query_array(the_column, '$.b[*].b1')
from the_table;

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

相关问题 SQL 转换 JSON:从 json 数组对象中选择一个字段 - SQL transform JSON: select one field from json array objects 如何从对象数组中选择字段值? - How to select field values from array of objects? 如何从 AWS Athena 中的 JSON 对象数组中提取字段? - How to extract a field from an array of JSON objects in AWS Athena? 从Postgres中的对象数组中选择一个具有特定字段所有值的数组 - Select an array with all the values of a particular field from an array of objects in Postgres 雪花:在雪花 SQL 中,我将如何从用户视图中看到 select 的单个字段并放入 JSON 格式? - Snowflake: In Snowflake SQL how would I select a single field from the users view and put into JSON format? 从 json 对象数组中转换 JSON: select 一行 - Transform JSON: select one row from array of json objects 如何在Ruby on Rails 2.3.14中从某个类的对象数组中选择某个字段 - How do I select a certain field from an array of objects of a certain class in Ruby on Rails 2.3.14 如何从JSON字段中选择字段 - How to select fields from a json field 在SQL中,如何从JSON字段中选择 - In sql, how to select from a json field 如何 select 记录与 json 字段数组中的值匹配? - How can I select records that match a value in a json field array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM