I am using the latest postgres 9.3, which has fancy support for json and also querying for a particular key inside a json field. But I am facing problems while updating a json field.
Basically, my json column is a dictionary which contains frequency of some fields, now since the fields are dynamic, I have put them in a json struct. Now I am facing trouble in an update query, where I just want to add the frequencies of corresponding fields of that json dict.
So, if I have sth like this - {"a":10, "b":2}, and while updating the incoming item is {"a":2,"c":3}, my new row should have {"a":12, "b":2, "c":3}
Appreciate your help.
You can do something like this in PostgreSQL:
update Test1 as t set
data = (
select
('{' || string_agg(a.data, ',') || '}')::json
from (
select '"' || a.key || '" :' || sum(a.value::int)::text as data
from (
select * from json_each_text(t.data)
union all
select * from json_each_text('{"a":2,"c":3}'::json) -- incoming
) as a
group by a.key
) as a
)
But may be easier way would be to write Python (or other PL) function.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.