Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select a row as JSON in Postgres

Tags:

postgresql

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
like image 916
Matt Hampel Avatar asked Aug 03 '16 22:08

Matt Hampel


People also ask

Which function converts a table row to JSON in PostgreSQL?

to_json() function Any SQL value can be converted to JSON using this PostgreSQL JSON function.

Can you query JSON in Postgres?

Postgres is a relational database that allows you to combine relational and non-relational data effortlessly, giving users/applications flexibility in accessing and handling the data. Additionally, Postgres includes native support for querying and processing JSON data.

How extract JSON data from PostgreSQL?

2) Querying PostgreSQL JSON Data To query data, you can use a SELECT statement like in any other SQL query. You can use the native PostgreSQL operators to query the data in PostgreSQL. The operator -> returns a JSON object field by key. The operator ->> returns a JSON object field by text.

How do I query JSON data?

To query JSON data, you can use standard T-SQL. If you must create a query or report on JSON data, you can easily convert JSON data to rows and columns by calling the OPENJSON rowset function. For more information, see Convert JSON Data to Rows and Columns with OPENJSON (SQL Server).


1 Answers

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
like image 182
Matt Hampel Avatar answered Sep 22 '22 06:09

Matt Hampel