Postgres 9.5更新内部json字段

时间:2017-09-05 05:22:51

标签: json postgresql

我有一个json专栏。该对象具有嵌套字段,例如

{
  "logo": {
    "url": "https://foo.bar"
    ...
  }
  ...
}

对象有更多字段,但url字段是我想要更新的字段。我相信我应该使用类似json_set的东西,但我对json路径感到迷茫。我能举个例子吗?

1 个答案:

答案 0 :(得分:1)

json只能使用jsonb进行此操作(但您可以轻松转换现有值)

使用jsonb_set,您需要提供要更改的对象的路径,以便'{logo,url}'

以下内容:

with t (data) as (
  values
    ('{
        "logo": { "url": "https://foo.bar", "something" : "some value"}, 
        "other" : { "one": "two"}
      }'::jsonb
    )
)
select jsonb_set(data, '{logo,url}', to_jsonb('http://bar.foo'::text))
from t;

WITH部分仅用于生成虚拟数据)

返回:

jsonb_set                                                                              
---------------------------------------------------------------------------------------
{"logo": {"url": "http://bar.foo", "something": "some value"}, "other": {"one": "two"}}

如您所见,只更换了url属性,其他所有内容都保持不变。

如果您的专栏真的是json,请使用your_column::jsonb以便您可以使用jsonb_set()

相关问题