1

I'm trying to add a new bool field in my JSON object throught jsonb request but it doesn't work. How should I change the request?

update source_settings   
    set settings = settings - 'isEnabled'   ||
                   jsonb_build_object('isEnabled', settings->'isEnabled')   
where settings ? 'isEnabled';
5
  • "it doesn't work" isn't a valid Postgres error message nor does it tell us what happens and what you expected to happen. But the expression makes no sense to me. First you remove the key, then you add the key with the existing value. Commented May 16, 2022 at 7:59
  • The "isEnabled" field doesn't added Commented May 16, 2022 at 8:02
  • Could you help explaining how to add binary values via jsonb? Commented May 16, 2022 at 8:03
  • 1
    Well, your WHERE clause will only update rows that already contain the isEnabled key. If you want to add it when it's not there, you would need where (not settings ? ...). And adding "binary" data is something completely different than "adding a boolean" value Commented May 16, 2022 at 8:08
  • settings->'isEnabled' doesn't really make sense as that will at best update it with the current value? Commented May 16, 2022 at 10:16

1 Answer 1

2

If you want to add a new key then just append it using ||

update source_settings   
    set settings = settings || jsonb_build_object('isEnabled', true)   
where not (settings ? 'isEnabled');

The WHERE clause will ensure that only rows are changed where the key does not exist. So rows where settingsalready contain "isEnabled" are not changed.

If the key doesn't exist, then using settings->'isEnabled' doesn't make sense as that will always return null

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.