mbatchkarov
mbatchkarov

Reputation: 16049

Postgres update JSON field

I've got several Postgres 9.4 tables that contain data like this:

| id | data                                      |
|----|-------------------------------------------|
| 1  | {"user": "joe", "updated-time": 123}      |
| 2  | {"message": "hi", "updated-time": 321}    |

I need to transform the JSON column into something like this

| id | data                                                         |
|----|--------------------------------------------------------------|
| 1  | {"user": "joe", "updated-time": {123, "unit":"millis"}}      |
| 2  | {"message": "hi", "updated-time": {321, "unit":"millis"}}    |

Ideally it would be easy to apply the transformation to multiple tables. Tables that contain the JSON key data->'updated-time' should be updated, and ones that do not should be skipped. Thanks!

Upvotes: 0

Views: 2160

Answers (1)

amphetamachine
amphetamachine

Reputation: 30595

You can use the || operator to merge two jsonb objects together.

select '{"foo":"bar"}'::jsonb || '{"baz":"bar"}'::jsonb;
= {"baz": "bar", "foo": "bar"}

Upvotes: 1

Related Questions