1

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.

2 Answers 2

1

Use json_each(), e.g.:

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)    
Sign up to request clarification or add additional context in comments.

2 Comments

How do I replace the hard-coded json value here with the query from my actual table?
Just skip with... and execute select ....
1
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.