1

Accepted answers elsewhere (How to push a JSON object to a nested array in a JSONB column) aren't working in my situation.

I want to append a string to a nested array in a not null JSONB column. If the array doesn't exist, I want to create it (and have my string added). The content of the column before the update happens will be an object {} (ie not an array).

The following just results in a null value in column "data" violates not-null constraint constraints error:

update md_ticker
SET data = jsonb_set(data, '{labels}', data -> 'labels' || '"some string"', true)
where id = 74650534

1 Answer 1

0

Use case to check whether the labels array exists:

update md_ticker
set data = case 
    when data ? 'labels' then 
        jsonb_set(data, '{labels}', data -> 'labels' || '"some string"', true)
    else
        data || '{"labels": ["some string"]}'
    end
where id = 74650534
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.