I'm struggling to find the right syntax for updating an array in a jsonb column in postgres 9.6.6

Given a column "comments", with this example:

    "Comment": "A",
    "LastModified": "1527579949"
    "Comment": "B",
    "LastModified": "1528579949"
    "Comment": "C",
    "LastModified": "1529579949"

If I wanted to append Z to each comment (giving AZ, BZ, CZ).

I know I need to use something like jsonb_set(comments, '{"Comment"}',

Any hints on finishing this off?




UPDATE elbat
       SET comments = array_to_json(ARRAY(SELECT jsonb_set(x.original_comment,
                                                 FROM (SELECT jsonb_array_elements(elbat.comments) original_comment) x))::jsonb;

It uses jsonb_array_elements() to get the array elements as set, applies the changes on them using jsonb_set(), transforms this to an array and back to json with array_to_json().

But that's an awful lot of work. OK, maybe there is a more elegant solution, that I didn't find. But since your JSON seems to have a fixed schema anyway, I'd recommend a redesign to do it the relational way and have a simple table for the comments plus a linking table for the objects the comment is on. The change would have been very, very easy in such a model for sure.

  • I agree that relational would make more sense. This is an existing database and my first encounter with postgres' jsonb data type. – Martin Flower Jun 4 '18 at 4:45

Find a query returning the expected result:

select jsonb_agg(value || jsonb_build_object('Comment', value->>'Comment' || 'Z'))
from my_table
cross join jsonb_array_elements(comments);

 [{"Comment": "AZ", "LastModified": "1527579949"}, {"Comment": "BZ", "LastModified": "1528579949"}, {"Comment": "CZ", "LastModified": "1529579949"}]
(1 row) 

Create a simple SQL function based of the above query:

create or replace function update_comments(jsonb)
returns jsonb language sql as $$
    from jsonb_array_elements($1)

Use the function:

update my_table
set comments = update_comments(comments);


  • Thank you @klin - so, use a function, do not use jsonb_set. – Martin Flower Jun 4 '18 at 4:42

Your Answer

