简体   繁体   中英

How to select single field from array of json objects?

I have a JSONB column with values in following JSON structure

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

I need to select only b1 field in the result. So expected result would be

["value2", "value5"]

I can select complete array using query

select columnname->>'b' from tablename

step-by-step demo: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
  2. a) get the b1 values from the array elements (b) reaggregate these values into a new JSON array

If you are using Postgres 12 or later, you an use a JSON path query:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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