Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update Postgresql table straight from a JSON object

I use

select to_json(host) from host where id=3

to query data from my postgreSQL database the result is like:

{"id":3,"project_id":1,"name":"a","mac":"abc","info":"x"}

after altering the data in my application I want to update the table.

Is there a "json"-way to do this? Not doing a ordinary update like

update host set project_id=1, name='a', mac='abc',info='x' where id=1;
like image 497
user2071938 Avatar asked Feb 16 '17 12:02

user2071938


People also ask

How do I query JSON data in PostgreSQL?

Querying the JSON documentPostgreSQL has two native operators -> and ->> to query JSON documents. The first operator -> returns a JSON object, while the operator ->> returns text. These operators work on both JSON as well as JSONB columns. There are additional operators available for JSONB columns.

Can we insert JSON data into PostgreSQL?

Some of the popular Operators useful for inserting JSON into PostgreSQL are: -> Operator: It enables you to select an element from your table based on its name. Moreover, you can even select an element from an array using this operator based on its index.


1 Answers

Use jsonb_populate_record in the update from clause

update host
set
    (project_id, name, mac, info) =
    (j.project_id, j.name, j.mac, j.info)
from jsonb_populate_record ( null::host,
    '{"id":1,"project_id":1,"name":"a","mac":"abc","info":"x"}'::jsonb
) j
where host.id = j.id
like image 70
Clodoaldo Neto Avatar answered Oct 05 '22 18:10

Clodoaldo Neto