json - 更新 Postgresql 中 JSON 字段中的嵌套标记

标签 json postgresql

我有以下 JSON 字段:

{
    "Id": "64848e27-c25d-4f15-99db-b476d868b575",
    "Associations_": [
        "RatingBlockPinDatum"
    ],
    "RatingScenarioId": "00572f95-9b81-4f7e-a359-3df06b093d4d",
    "RatingBlockPinDatum": [
        {
            "Name": "mappedmean",
            "PinId": "I.Assessment",
            "Value": "24.388",
            "BlockId": "Score"
        },
        {
            "Name": "realmean",
            "PinId": "I.Assessment",
            "Value": "44.502",
            "BlockId": "Score"
        }]}

我想将值从 24.388 更新为嵌套数组“RatingBlockPinDatum”中的新值,其中 Name =“mappedmean”。

如有任何帮助,我们将不胜感激。我已经尝试过了,但无法使其正常工作:

[ Update nested key with postgres json field in Rails

最佳答案

您可以先为 RatingBlockPinDatum JSON 数组中的每个元素获取一个结果(使用 jsonb_array_lengthgenerate_series),然后根据 where 过滤该结果Name 键的值为“mappedmean”。然后你有需要更新的记录。更新本身可以通过 jsonb_set 完成:

with cte as (
    select id, generate_series(0, jsonb_array_length(info->'RatingBlockPinDatum')-1) i
    from   mytable
)
update mytable
   set info = jsonb_set(mytable.info, 
                 array['RatingBlockPinDatum', cte.i::varchar, 'Value'], 
                 '"99.999"'::jsonb)
from   cte
where  mytable.info->'RatingBlockPinDatum'->cte.i->>'Name' = 'mappedmean'
and    cte.id = mytable.id;

将“99.999”替换为您要存储在该 Value 属性中的任何值。

查看它在 rextester.com 上运行

关于json - 更新 Postgresql 中 JSON 字段中的嵌套标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48487479/

相关文章:

python - 区分大小写的查询返回字符串而不是列表

sql - PostgreSQL:是否可以打印正在运行的查询的查询计划?

javascript - 根据属性删除 JSON 对象

postgresql - 在 2 个 heroku 应用程序之间共享一个 heroku basic postgres DB

javascript - forEach 不是函数 javascript

javascript - Vuejs 从数据属性返回 [object Object]

sql - 使用函数子查询更快

postgresql - Postgres : problem with FK contraint

javascript - jQuery .html() 的回调函数?

javascript - 从 JSON 对象获取值