I have a table containing a json column. The json values will look something like this:
{'john': 1, 'alex' : 4, 'harry' :2}
If I wanted to add 1 to john, how would I go about doing this?
I have a table containing a json column. The json values will look something like this:
{'john': 1, 'alex' : 4, 'harry' :2}
If I wanted to add 1 to john, how would I go about doing this?
UPDATE mytable -- 6
SET mydata = jsonb_set( -- 4
mydata::jsonb, -- 1
'{john}', -- 2
((mydata ->> 'john')::int + 1)::text::jsonb -- 3
)::json; -- 5
json
, cast it into type jsonb
text
array->>
operator returns type text
, so to do an integer
operation, you need to cast it into type int
. Then add the 1
. This result must be reconverted into type jsonb
. Unfortunately type int
cannot be cast into type jsonb
directly, so take the intermediate step via type text
jsonb_set()
to update the JSON object specified in (1)json
instead of jsonb
, cast the result back into type json