'Copy JSONB property data within a collection

I have a JSONB column with data as follows:

{
  "foo": {
    "bars": [
       { "propA": "abc" },
       { "propA": "def" }
    ]
  }
}

For each element in bars, I'm trying to copy the value from propA into a new propB property. Basically the resulting JSON needs to look like this:

{
  "foo": {
    "bars": [
       { "propA": "abc", "propB": "abc" },
       { "propA": "def", "propB": "def" }
    ]
  }
}

Is this possible to do via an UPDATE statement?

Thank you.



Solution 1:[1]

dbfiddle link for demonstration.

SQL that will change the jsonb object:

SELECT id,
       Jsonb_set(final_inline_view.contentx, '{foo,bars}',
       final_inline_view.synthesized_jsonb_agg) changed_jsonb
FROM   (SELECT id,
               contentx,
               Jsonb_agg (Jsonb_build_object('PropA', z.x, 'PropB', z.x))
                      synthesized_jsonb_agg
        FROM   (SELECT jsonsettest.id,
                       jsonsettest.content contentx,
                       Jsonb_array_elements(Jsonb_path_query_array(content,
                                            '$.foo.bars[0,1]'))
                               ->>
                       'propA'             x
                FROM   jsonsettest) z
        GROUP  BY id,
                  contentx) final_inline_view;      

Update (final):

UPDATE jsonsettest a
SET    content = b.changed_jsonb
FROM   (SELECT id,
               Jsonb_set(final_inline_view.contentx, '{foo,bars}',
               final_inline_view.synthesized_jsonb_agg) changed_jsonb
        FROM   (SELECT id,
                       contentx,
                       Jsonb_agg (Jsonb_build_object('PropA', z.x, 'PropB',
                       z.x))
                               synthesized_jsonb_agg
                FROM   (SELECT jsonsettest.id,
                               jsonsettest.content contentx,
                               Jsonb_array_elements(Jsonb_path_query_array(
                                                    content,
                                                    '$.foo.bars[0,1]'))
                                       ->>
                               'propA'             x
                        FROM   jsonsettest) z
                GROUP  BY id,
                          contentx) final_inline_view) b
WHERE  a.id = b.id; 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1