7

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;
4
  • You are looking for the update statement. Commented Feb 16, 2017 at 12:47
  • sure, but I want to know if there is a way to use the json directly in the update statement Commented Feb 16, 2017 at 12:48
  • 2
    Yes, that's possible. But without more details this is impossible to answer. Please Edit your question and add some sample data and the expected output based on that data. Formatted text please, no screen shots Commented Feb 16, 2017 at 13:20
  • There is no way you can avoid the set column = value syntax. UPDATE simply doesn't support that. Commented Feb 16, 2017 at 13:43

1 Answer 1

9

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
Sign up to request clarification or add additional context in comments.

2 Comments

Just wondering why jsonb_populate_record over json_populate_record? Also, can either json update function somehow ignore a null field in the JSON, i.e. don't update if JSON is null?
A little late to the party, but in case someone else needs to remove null fields, check out jsonb_strip_nulls postgresql.org/docs/current/functions-json.html

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.