'Adding boolean field in JSONB

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';


Solution 1:[1]

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

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 a_horse_with_no_name