0

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!

4
  • Do you have any queries that you've tried? Where are you stuck exactly? With the right operators / functions to use for the JSON manipulation? With the basic SQL for updating a selection of rows based on a condition? Commented May 5, 2016 at 13:51
  • 2
    The provided expected json is not valid, you could use {"value": 123, "unit":"millis"} or [123, {"unit":"millis"}]. Commented May 5, 2016 at 13:51
  • 2
    Possible duplicate of How do I modify fields inside the new PostgreSQL JSON datatype? Commented May 5, 2016 at 13:52
  • If I was you I would just write a python script to do the conversion Commented May 6, 2016 at 3:20

1 Answer 1

1

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

select '{"foo":"bar"}'::jsonb || '{"baz":"bar"}'::jsonb;
= {"baz": "bar", "foo": "bar"}
Sign up to request clarification or add additional context in comments.

Comments

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.