简体   繁体   中英

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!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM