I need to write SQL code, that INSERT into some table data, that stored in another table as JSON. PostgreSQL 9.5.
I have a table named comments. It has a JSON colum refs with data like this:
[{"author":"John","tags":["ruby","rails"]}, {"author":"Nick","tags":["sql"]}]
As you can see, there maybe more than one item (pair) in the JSON.
I need to write SQL code, that will take all the records from comments where refs IS NOT NULL and INSERT INTO comments_refs (dont ask why am I need it :) ), that looks like:
id | integer | not null default nextval(...)
comment_id | integer | not null
author | character varying(255) | not null
tags | text[] | not null default '{}'::text[]
I try to play with json_to_recordset, but it doesn't work with arrays (see http://postgresql.nabble.com/bug-in-json-to-record-with-arrays-td5828415.html ). Next, I try something like:
SELECT json_array_elements(rec.refs) FROM comments AS rec;
but I do not come up with how to do it .. Maybe somebody can help me. Thanks.