【问题标题】:update each value in json array更新json数组中的每个值
【发布时间】:2022-10-20 19:34:52
【问题描述】:

我有一个目前看起来像这样的表:

id tags
1 {"key1" : "val1", "key2" : "val2" }

我希望它看起来像这样:

id tags
1 {"key1" : ["val1"], "key2" : ["val2"] }

我不确定如何编写一个 PSQL 查询来转换 json 数组中的每个值。

【问题讨论】:

    标签: json postgresql sql-update


    【解决方案1】:
    -- simple way 
    select jsonb_object_agg(t.a, jsonb_build_array(t.b)) from jsonb_each_text('{"key1" : "val1", "key2" : "val2" }'::jsonb) as t(a, b)
    
    
    -- for multiple json rows
    with t1(id, jsondata) as 
    (
        select 1, '{"key1" : "val1", "key2" : "val2" }'::jsonb
        union all 
        select 2, '{"key1" : "val3", "key2" : "val4" }'::jsonb
    ) 
    select t1.id, jsonb_object_agg(t2.a, jsonb_build_array(t2.b)) from t1 
    cross join jsonb_each_text(t1.jsondata) t2(a, b)
    group by t1.id 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-13
      • 1970-01-01
      • 2022-08-17
      • 2022-01-04
      • 2017-09-19
      • 1970-01-01
      • 2018-08-07
      • 2020-08-22
      相关资源
      最近更新 更多