简体   繁体   中英

Extract all values from json in sql table

I have a postgresql table which has a column in json format.

Sample column value:

{"Apple":{"category":"fruit","price":100},"Orange":{"category":"fruit","price":80}}

Now I want to select this column, and extract the "price" for all items in each row.

Query to get column:

select items from my_table

To extract the json value for a specific item, I can use

select items -> 'Orange' -> 'price' as price
from my_table

But how do I extract the price for all the items (Apple, Orange)? As an array maybe.

Use json_each() , eg:

with my_table(items) as (
    values (
    '{"Apple":{"category":"fruit","price":100},"Orange":{"category":"fruit","price":80}}'::json
    )
)

select key, (value->>'price')::numeric as price
from my_table,
json_each(items)

  key   | price 
--------+-------
 Apple  |   100
 Orange |    80
(2 rows)    
t=# with my_table(items) as (
  values('{"Apple":{"category":"fruit","price":100},"Orange":{"category":"fruit","price":80}}'::json)
)
select
  json_object_keys(items)
, items->json_object_keys(items)->>'price'
from my_table;
 json_object_keys | ?column?
------------------+----------
 Apple            | 100
 Orange           | 80
(2 rows)

json_object_keys : https://www.postgresql.org/docs/9.5/static/functions-json.html

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