108

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. Commented Apr 16, 2020 at 19:44

2 Answers 2

173

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

Sign up to request clarification or add additional context in comments.

5 Comments

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 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.
Use data::json->>'name' if you don't want double quotes around strings. postgresql.org/docs/current/functions-json.html
trim('"' FROM (data::json->'name')::text) in order to remove quotes
any solution for the case when one doesn't know structure of the underlying json blob?
76

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;

1 Comment

or like this if you want to access nested objects: data::json#>'{author,last_name}' as author

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.