【问题标题】:Update nested tag in JSON field in Postgresql更新 Postgresql 中 JSON 字段中的嵌套标签
【发布时间】:2018-01-28 23:56:34
【问题描述】:

我有以下 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

【问题讨论】:

  • 你的字段的数据类型是json还是jsonb。如果不是jsonb,您可以将其转换为那个,还是需要为json 工作?
  • @trincot 数据类型为jsonb

标签: json postgresql


【解决方案1】:

您可以首先在RatingBlockPinDatum JSON 数组中为每个元素获取一个结果(使用jsonb_array_lengthgenerate_series),然后过滤该结果以找出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上运行

【讨论】:

    猜你喜欢
    • 2021-10-30
    • 2019-04-24
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 2015-03-05
    相关资源
    最近更新 更多