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;
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With