Let's say we got this jsonb
{
"animals": [
{"name": "Cat", "age": 5},
{"name": "Dog", "age": 10}
]
}
We want to update the age of Cat from 5 to 15. The function jsonb_set(...) returns a new jsonb with updated value.
select
jsonb_set(
'{"animals": [{"name": "Cat", "age": 5}, {"name": "Dog", "age": 10}]}',
'{animals,0,age}', -- Path to the field to update
'15'::jsonb, -- New value to set
false -- If true, this will make a new key if it doesn't exist in the jsonb
)
;
If you would like to do something like that in an SQL update, this would go like;
update animals
set
animals_metadata = jsonb_set(animals_metadata, '{animals,0,age}', to_jsonb(15), false)
where id = '123';
Check out the official documentation for more!
set attr['is_default'] = to_jsonb('my_text'::text)– Petri Ryhänen May 04 '23 at 09:01