简体   繁体   中英

Query values from each json in a json array on postgresql

Each record in my database has a json list, from which I'm trying to return a value inside each element.

I'm trying to return

environmental services, energy & utilities

From

[
  {
    "key": "environmental services"
  },
  {
    "key": "energy & utilities"
  }
]

And.

construction

From

[
  {
    "key": "construction"
  }
]

Where the length of each json list in each record is undetermined.

I can get the first value with:

select
  column_name -> 0 -> 'key'
from table

But how to get all.

How can I do this in postgresql?

Use the function jsonb_array_elements() in a lateral join to get all elements of the arrays and the aggregate function string_agg() :

with my_table(json_col) as (
values
('[
  {
    "key": "environmental services"
  },
  {
    "key": "energy & utilities"
  }
]'::jsonb),
('[
  {
    "key": "construction"
  }
]')
)

select string_agg(value->>'key', ', ')
from my_table
cross join jsonb_array_elements(json_col)
group by json_col       -- use PK here (if exists)

                 string_agg                 
--------------------------------------------
 environmental services, energy & utilities
 construction
(2 rows)

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