How do I modify fields inside the new PostgreSQL JSON datatype?

前端 未结 21 1973
孤独总比滥情好
孤独总比滥情好 2020-11-22 15:37

With postgresql 9.3 I can SELECT specific fields of a JSON data type, but how do you modify them using UPDATE? I can\'t find any examples of this in the postgresql documenta

21条回答
  •  失恋的感觉
    2020-11-22 16:28

    So, for example my string looks like this: {"a1":{"a11":"x","a22":"y","a33":"z"}}

    I update jsons by using temp table, which is good enough for rather small ammounth of data (<1.000.000). I found a different way, but then went on vacation and forgot it...

    So. the query will be something like this:

    with temp_table as (
    select 
    a.id,
    a->'a1'->>'a11' as 'a11',
    a->'a1'->>'a22' as 'a22',
    a->'a1'->>'a33' as 'a33',
    u1.a11updated
    from foo a
    join table_with_updates u1 on u1.id = a.id)
        update foo a
        set a = ('{"a1": {"a11": "'|| t.a11updated ||'",
            "a22":"'|| t.a22 ||'",
            "a33":"'|| t.a33 ||'"}}')::jsonb
        from temp_table t
        where t.id = a.id;
    

    It has more to do with string than json, but it works. Basically, it pulls all the data into temp table, creates a string while plugging concat holes with the data you backed up, and converts it into jsonb.

    Json_set might be more efficient, but I'm still getting a hang of it. First time I tried to use it, I messed up the string completely...

提交回复
热议问题