HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlModerate

Postgresql: Modify one value inside of a nested json column

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
postgresqlcolumnvaluenestedonejsonmodifyinside

Problem

I have a json column called "Parameters" in a "Assets" table. The jsons are nested and have the following structure:

{
"params1": {"k": 1.1, "efficiency": 0.7}, 
"params2": {"k": 1.9, "C_max": 100.0, "C_min": 10.0}
}


I would like to update only one value "k" in "params2" and keep the rest of the values unchanged. I tried with the following code:

update "Assets" 
set "Parameters" = "Parameters"::jsonb || '{"params2":{"k":2.2}}'::jsonb
where "Id" = 185;


This results in

{
"params1": {"k": 1.1, "efficiency": 0.7}, 
"params2": {"k": 2.2}
}


So the rest of the parameters in "params2" are dropped which is not desired. What would be a way to modify "k" and leave the rest as it is?

Solution

You are looking for jsonb_set() (documentation)

update "Assets" 
  set "Parameters" = jsonb_set("Parameters"::jsonb, '{params2, k}', to_jsonb(2.2))
where ...

Code Snippets

update "Assets" 
  set "Parameters" = jsonb_set("Parameters"::jsonb, '{params2, k}', to_jsonb(2.2))
where ...

Context

StackExchange Database Administrators Q#290260, answer score: 14

Revisions (0)

No revisions yet.