0

I am trying to update json

[{"id": "1", "name": "myconf", "icons": "small", "theme": "light", "textsize": "large"},
 {"id": 2, "name": "myconf2", "theme": "dark"}, {"name": "firstconf", "theme": "dark", "textsize": "large"},
 {"id": 3, "name": "firstconxsf", "theme": "dassrk", "textsize": "lassrge"}]

and this is the table containing that json column :

CREATE TABLE USER_CONFIGURATIONS ( ID BIGSERIAL PRIMARY KEY, DATA JSONB ); 

adding new field is easy I am using:

UPDATE USER_CONFIGURATIONS
SET DATA = DATA || '{"name":"firstconxsf", "theme":"dassrk", "textsize":"lassrge"}'
WHERE id = 9;

But how to update single with where id = 1 or 2

2
  • CREATE TABLE USER_CONFIGURATIONS ( ID BIGSERIAL PRIMARY KEY, DATA JSONB ); Commented Nov 18, 2019 at 10:10
  • i am following idalko.com/crud-operations-postgres-jsonb this is easy when you are trying to add with one key with list. Commented Nov 18, 2019 at 10:10

1 Answer 1

1

Click: step-by-step demo:db<>fiddle

UPDATE users                                                   -- 4
SET data = s.updated
FROM (
    SELECT
        jsonb_agg(                                             -- 3
            CASE                                               -- 2
                WHEN ((elem ->> 'id')::int IN (1,2)) THEN
                    elem || '{"name":"abc", "icon":"HUGE"}'
                ELSE elem
            END
        ) AS updated
    FROM
        users,
        jsonb_array_elements(data) elem                        -- 1
) s;
  1. Expand array elements into one row each
  2. If element has relevant id, update with || operator; if not, keep the original one
  3. Reaggregate the array after updating the JSON data
  4. Execute the UPDATE statement.
Sign up to request clarification or add additional context in comments.

5 Comments

is that possible we can put condition in to check where id = 321 on table id
You simply can add a WHERE clause:dbfiddle.uk/…
dbfiddle.uk/… its adding one more value with same id and updating existing.
Currently all expanded values of all array rows will be aggregated. For this, of course, you need a grouping: dbfiddle.uk/…
Did this help? Please do not forget to upvote ALL helpful answers (which honors the work and time the repliers invested into your question) and accept the best fitting answer (to close the question). Otherwise please tell us, what to change.

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.