2

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for taking the time ! I think I prefer the pl/python approach. Much cleaner and easier to maintain.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.