如何修改新的PostgreSQL JSON数据类型中的字段?

380

使用postgresql 9.3,我可以使用SELECT选择JSON数据类型的特定字段,但如何使用UPDATE修改它们?在postgresql文档或任何在线资源中,我都找不到任何关于此的示例。我已经尝试了显而易见的方法:

postgres=# create table test (data json);
CREATE TABLE
postgres=# insert into test (data) values ('{"a":1,"b":2}');
INSERT 0 1
postgres=# select data->'a' from test where data->>'b' = '2';
 ?column?
----------
 1
(1 row)
postgres=# update test set data->'a' = to_json(5) where data->>'b' = '2';
ERROR:  syntax error at or near "->"
LINE 1: update test set data->'a' = to_json(5) where data->>'b' = '2...
24个回答

0
select * from pg_settings where name = 'deadlock_timeout';
begin;
create temp table a2(data jsonb);
insert into a2 values('{
    "key0": {
        "key01": "2018-05-06T12:36:11.916761+00:00",
        "key02": "DEFAULT_WEB_CONFIGURATION",
    "key1": {
        "key11": "Data System",
        "key12": "<p>Health,<p>my address<p>USA",
        "key13": "*Please refer to main screen labeling"
    }
}}'::jsonb);
commit;

嵌套的jsonb结构更新。可以用于删除。

update a2 set data =
    data::jsonb #-  '{key0, key1, key13}'
        || '{"key13":"screen labeling"}'::jsonb
returning *;

0

如果您想在JSON更新命令中使用其他列的值,可以使用字符串连接:

UPDATE table
SET column1 = column1::jsonb - 'key' || ('{"key": ' || column2::text ||  '}')::jsonb
where ...;

0

例如,我的字符串看起来像这样: {"a1":{"a11":"x","a22":"y","a33":"z"}}

我使用临时表更新jsons,对于相当小的数据量(<1,000,000)来说,这已经足够好了。我找到了一种不同的方法,但后来去度假忘记了...

所以,查询将类似于这样:

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;

这与json关系不大,更多的是与字符串有关,但它可以工作。基本上,它将所有数据拉入临时表中,创建一个字符串并插入已备份数据的连接孔,然后转换为jsonb。

Json_set可能更高效,但我还需要熟悉它。第一次尝试使用它时,我彻底弄乱了字符串...


1
你好,欢迎来到StackOverflow!请注意,这个问题已经有一个被接受的答案了。 - hongsy
请注意,根据字段内容,此方法存在安全漏洞的潜在风险,因为您需要将数据编码为JSON字符串,否则攻击者可能会操纵您的数据结构。 - Mikko Rantalainen

0

对于使用mybatis的人来说,这是一个更新语句的示例:

<update id="saveAnswer">
    update quiz_execution set answer_data = jsonb_set(answer_data, concat('{', #{qid}, '}')::text[], #{value}::jsonb), updated_at = #{updatedAt}
    where id = #{id}
</update>


参数:

  • qid,字段的键。
  • value,是一个有效的 JSON 字符串,用于字段值,
    例如通过 jackson 从对象转换为 JSON 字符串,

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接