0

I have a table, let's call it myTable with the following structure

ID   | data
____________
uuid | jsonb

The data in the jsonb field is an array structured in the following way:

[
  {
    "valueA": "500",
    "valueB": "ABC",
  },
  {
    "valueA": "300",
    "valueB": "CDE",
  }
]

What I want to do is transform that data by converting valueB to be an object, with newKey that corresposnds to the current value of "valueB"

This is the result I want:

[
  {
    "valueA": "500",
    "valueB": {"newKey": "ABC"},
  },
  {
    "valueA": "300",
    "valueB": {"newKey": "CDE"},
  }
]

I tried doing it with the following query:

UPDATE myTable
SET data = (
    SELECT jsonb_agg (
        jsonb_insert(elems, '{valueB, newKey}', elems->'valueB')
    )
    FROM jsonb_array_elements(data) elems
);

It doesn't seem to do anything unfortunately.

Another idea I have is to create a new field, initialize it as an object, then delete the old onde and rename the new one, but it seems there must be a way to do what I want directly?

1 Answer 1

1

Solved using jsonb_build_object()

UPDATE myTable
SET data = (
    SELECT jsonb_agg (
        jsonb_insert(elems, '{valueB}', jsonb_build_object('newKey', elems->'valueB'))
    )
    FROM jsonb_array_elements(data) elems
);
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.