13

Is there a straightforward way to put entire row from one Postgres table into a JSON column in another table?

Here's an example to illustrate what I'm looking to do. Let's say I've got a table people, with name, age, and data columns:

column type
-----------
name   text
age    int
data   json

I'd like to merge in my table of 2012_customers, which has a lot more columns. How would I stuff all those extra columns into the JSON column of people, preserving the column names as the data keys? Here's some pseudo-SQL for that:

insert into people
select 
name,
age,
all_fields_as_json() as json
from customers_2012
4
  • 1
    Does row_to_json not do what you need? Commented Aug 3, 2016 at 22:09
  • That or to_json probably does what I want, but I haven't been able to figure out the correct syntax for the example above. Commented Aug 3, 2016 at 22:24
  • 1
    try select name, age, row_to_json(customers_2012) from customers_2012 as your select part. Commented Aug 3, 2016 at 22:25
  • Got that just as you posted! Thanks! If you want to post the answer I'll remove mine and accept yours. Commented Aug 3, 2016 at 22:28

1 Answer 1

22

In this situation, the correct syntax is to use row_to_json(table_name):

insert into people
select 
name,
age,
row_to_json(customers_2012) as json
from customers_2012
Sign up to request clarification or add additional context in comments.

2 Comments

Small addition: When qualifying the schema on the FROM statement, the schema does not get qualified in the row_to_json() call This means it looks like this sql select row_to_json(mytable) as json from other_schema.mytable;
You can get it working with a table on non-default schema by aliasing the table. sql select row_to_json(t) as json from other_schema.mytable t

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.