68

I have a table in my database, which contains character varying column and this column has json. I need to write a query, which will somehow parse this json into separate columns.

I found json_each function here but I can't understand how to work with it.

1
  • PostgreSQL supports native JSON data type since version 9.2.
    – WEBjuju
    Apr 16, 2020 at 19:44

2 Answers 2

112

I figured it out, guys

if I have a table books enter image description here

I can easily write a query

SELECT 
   id, 
   data::json->'name' as name
FROM books;

And it will result in

enter image description here

I can also try to get non-existent column

SELECT 
   id, 
   data::json->'non_existant' as non_existant
FROM books;

And it this case I will get empty result

enter image description here

5
  • 3
    If you're on a recent-enough version of postgres, using data::jsonb->'foo' will be slightly more efficient (with 'json' it actually gets re-parsed for every element access).
    – Dmitri
    Sep 17, 2015 at 15:08
  • 2
    @Dmitri In this context it would with data::jsonb too. You'd only benefit if you wrapped it in subquery and referenced the casted result from the inner query multiple times in the outer query. Sep 18, 2015 at 4:41
  • 8
    Use data::json->>'name' if you don't want double quotes around strings. postgresql.org/docs/current/functions-json.html Oct 10, 2019 at 9:42
  • 1
    trim('"' FROM (data::json->'name')::text) in order to remove quotes Mar 11 at 9:03
  • any solution for the case when one doesn't know structure of the underlying json blob?
    – jayarjo
    Jun 6 at 7:34
47

Awesome, thanks for sharing. I found that you can go deeper like:

SELECT 
   id, 
   data::json->'name' as name,
   data::json->'author' ->> 'last_name' as author
FROM books;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.