Update postgres json value by other attribute I'm using PostgreSQL 9.6 and
I got the following table:
Cars
ID          Name        Data 
 1           abc        {&quot;color&quot;:&quot;red&quot;,&quot;wheels&quot;:4,&quot;my-value&quot;:false}
 2           def        {&quot;color&quot;:&quot;blue&quot;,&quot;wheels&quot;:8}
 3           xyz        {&quot;color&quot;:&quot;yellow&quot;,&quot;my-value&quot;:true}

I want to extend the Data JSON object by adding another boolean attribute called &quot;new-attr&quot; which should get the exact value of &quot;my-value&quot; of the JSON field.
for example, if &quot;my-value&quot; in ID 1 is false, then &quot;new-attr&quot; will be false.
And if not set, do not add it at all (as in number 2).
I tried the following but it didn't help:
UPDATE cars SET data=jsonb_set(data,'{new-attr}',data-&gt;'my-value')

I expect to get the following JSON :
 ID          Name        Data
1           abc        {&quot;color&quot;:&quot;red&quot;,&quot;wheels&quot;:4,&quot;my-value&quot;:false,&quot;new-attr&quot;:false} // same value
2           def        {&quot;color&quot;:&quot;blue&quot;,&quot;wheels&quot;:8} // no change
3           xyz        {&quot;color&quot;:&quot;yellow&quot;,&quot;my-value&quot;:true,&quot;new-attr&quot;:true} // same value true

Any suggestions ?
The concatenation operator || will do that:
update the_table
  set data = data || jsonb_build_object('new-attr', data -&gt; 'my-value')
where data ? 'my-value'; --&lt;&lt; only update rows that contain the key

The ? operator tests if the key is present in the JSON value.

If your column is defined as json (rather than jsonb which it should be), you probably need to cast it, to make the || operator work properly: data::jsonb || ...