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

时间:2013-08-13 12:51:27

标签: json postgresql postgresql-9.3 postgresql-json

使用postgresql 9.3我可以选择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...

21 个答案:

答案 0 :(得分:261)

更新With PostgreSQL 9.5,PostgreSQL内部有一些jsonb操作功能(但json没有;操纵{{1} }))。

合并2个(或更多)JSON对象(或连接数组):

json

因此,设置一个简单的密钥可以使用:

完成
SELECT jsonb '{"a":1}' || jsonb '{"b":2}', -- will yield jsonb '{"a":1,"b":2}'
       jsonb '["a",1]' || jsonb '["b",2]'  -- will yield jsonb '["a",1,"b",2]'

SELECT jsonb '{"a":1}' || jsonb_build_object('<key>', '<value>') 应该是字符串,<key>可以是<value>接受的任何类型。

对于在JSON层次结构中设置深层值,可以使用to_jsonb()函数:

jsonb_set()

SELECT jsonb_set('{"a":[null,{"b":[]}]}', '{a,1,b,0}', jsonb '{"c":3}') -- will yield jsonb '{"a":[null,{"b":[{"c":3}]}]}' 的完整参数列表:

jsonb_set()

jsonb_set(target jsonb, path text[], new_value jsonb, create_missing boolean default true) 也可以包含JSON数组索引&amp;出现在那里的负整数从JSON数组的末尾开始计算。但是,不存在但肯定的JSON数组索引会将元素追加到数组的末尾:

path

对于插入JSON数组(同时保留所有原始值),可以使用SELECT jsonb_set('{"a":[null,{"b":[1,2]}]}', '{a,1,b,1000}', jsonb '3', true) -- will yield jsonb '{"a":[null,{"b":[1,2,3]}]}' 函数( in 9.6+;此函数仅在本节中使用):

jsonb_insert()

SELECT jsonb_insert('{"a":[null,{"b":[1]}]}', '{a,1,b,0}', jsonb '2') -- will yield jsonb '{"a":[null,{"b":[2,1]}]}', and SELECT jsonb_insert('{"a":[null,{"b":[1]}]}', '{a,1,b,0}', jsonb '2', true) -- will yield jsonb '{"a":[null,{"b":[1,2]}]}' 的完整参数列表:

jsonb_insert()

同样,jsonb_insert(target jsonb, path text[], new_value jsonb, insert_after boolean default false) 中出现的负整数从JSON数组的末尾算起。

所以,f.ex。附加到JSON数组的末尾可以使用:

path

但是,当SELECT jsonb_insert('{"a":[null,{"b":[1,2]}]}', '{a,1,b,-1}', jsonb '3', true) -- will yield jsonb '{"a":[null,{"b":[1,2,3]}]}', and 中的jsonb_set()是JSON对象的键时,此函数的工作方式略有不同(而不是path)。在这种情况下,它只会在未使用密钥时为JSON对象添加新的键值对。如果使用它,将引发错误:

target

可以使用SELECT jsonb_insert('{"a":[null,{"b":[1]}]}', '{a,1,c}', jsonb '[2]') -- will yield jsonb '{"a":[null,{"b":[1],"c":[2]}]}', but SELECT jsonb_insert('{"a":[null,{"b":[1]}]}', '{a,1,b}', jsonb '[2]') -- will raise SQLSTATE 22023 (invalid_parameter_value): cannot replace existing key 运算符从JSON对象(或从数组中)删除键(或索引)

-

可以使用SELECT jsonb '{"a":1,"b":2}' - 'a', -- will yield jsonb '{"b":2}' jsonb '["a",1,"b",2]' - 1 -- will yield jsonb '["a","b",2]' 运算符从JSON层次结构深处删除

#-

对于9.4 ,您可以使用原始答案的修改版本(如下所示),但不是聚合JSON字符串,而是直接使用SELECT '{"a":[null,{"b":[3.14]}]}' #- '{a,1,b,0}' -- will yield jsonb '{"a":[null,{"b":[]}]}' 聚合到json对象中。

原始答案:纯SQL中也可以(没有plpython或plv8)(但需要9.3+,不能用于9.2)

json_object_agg()

SQLFiddle

修改

一个版本,设置多个键和值:

CREATE OR REPLACE FUNCTION "json_object_set_key"(
  "json"          json,
  "key_to_set"    TEXT,
  "value_to_set"  anyelement
)
  RETURNS json
  LANGUAGE sql
  IMMUTABLE
  STRICT
AS $function$
SELECT concat('{', string_agg(to_json("key") || ':' || "value", ','), '}')::json
  FROM (SELECT *
          FROM json_each("json")
         WHERE "key" <> "key_to_set"
         UNION ALL
        SELECT "key_to_set", to_json("value_to_set")) AS "fields"
$function$;

编辑2 :作为@ErwinBrandstetter noted上面的这些函数就像所谓的CREATE OR REPLACE FUNCTION "json_object_set_keys"( "json" json, "keys_to_set" TEXT[], "values_to_set" anyarray ) RETURNS json LANGUAGE sql IMMUTABLE STRICT AS $function$ SELECT concat('{', string_agg(to_json("key") || ':' || "value", ','), '}')::json FROM (SELECT * FROM json_each("json") WHERE "key" <> ALL ("keys_to_set") UNION ALL SELECT DISTINCT ON ("keys_to_set"["index"]) "keys_to_set"["index"], CASE WHEN "values_to_set"["index"] IS NULL THEN 'null'::json ELSE to_json("values_to_set"["index"]) END FROM generate_subscripts("keys_to_set", 1) AS "keys"("index") JOIN generate_subscripts("values_to_set", 1) AS "values"("index") USING ("index")) AS "fields" $function$; 一样(如果字段存在则更新字段,如果字段不存在则插入) 。这是一个变体,只有UPSERT

UPDATE

编辑3 :这是递归变体,可以设置(CREATE OR REPLACE FUNCTION "json_object_update_key"( "json" json, "key_to_set" TEXT, "value_to_set" anyelement ) RETURNS json LANGUAGE sql IMMUTABLE STRICT AS $function$ SELECT CASE WHEN ("json" -> "key_to_set") IS NULL THEN "json" ELSE (SELECT concat('{', string_agg(to_json("key") || ':' || "value", ','), '}') FROM (SELECT * FROM json_each("json") WHERE "key" <> "key_to_set" UNION ALL SELECT "key_to_set", to_json("value_to_set")) AS "fields")::json END $function$; )叶子值(并使用此答案中的第一个函数),位于关键路径(其中)键只能引用内部对象,不支持内部数组):

UPSERT

更新:功能现在已经压缩。

答案 1 :(得分:64)

使用9.5使用jsonb_set -

if(jQuery('.<?=str_replace(' ','_',$levels[ $i + 1 ])?>_startSelect').size()) {
            var url = getUrl( jQuery(this).parent('form'), '<?=str_replace(' ','_',$levels[ $i + 1 ])?>' );
            alert(jQuery('.<?=str_replace(' ','_',$levels[ $i + 1 ])?>_startSelect').val());
            jQuery(this).nextAll('.<?=str_replace(' ','_',$levels[ $i + 1 ])?>_startSelect').html( loadingText );
            jQuery(this).nextAll('.<?=str_replace(' ','_',$levels[ $i + 1 ])?>_endSelect').html( loadingText );
            jQuery(this).nextAll('.<?=str_replace(' ','_',$levels[ $i + 1 ])?>_startSelect').load( url, {}, function(responseText) {
                jQuery(this).html(responseText);
                callbackFunc.apply( this );
            });  
            jQuery(this).nextAll('.<?=str_replace(' ','_',$levels[ $i + 1 ])?>_endSelect').load( url, {}, function(responseText) {
                jQuery(this).html(responseText);
                callbackFunc.apply( this );
            });
        } else {
            if(jQuery('.<?=str_replace(' ','_',$levels[ $i ])?>Select').val() != "0")
            {
              var url = getUrl( jQuery(this).parent('form'), '<?=str_replace(' ','_',$levels[ $i + 1 ])?>' );
              var NewVar = jQuery(this).nextAll('.<?=str_replace(' ','_',$levels[ $i + 1 ])?>Select').html( loadingText );
              jQuery(this).nextAll('.<?=str_replace(' ','_',$levels[ $i + 1 ])?>Select').html( loadingText );
              jQuery(this).nextAll('.<?=str_replace(' ','_',$levels[ $i + 1 ])?>Select').load( url, {}, function(responseText) {
                jQuery(this).html(responseText);
                callbackFunc.apply( this );
              });
            }
            else
            {
              //jQuery(this).nextAll('.<?=str_replace(' ','_',$levels[ $i + 1 ])?>Select').html('<option></option>').attr('disabled','disabled');
              //jQuery(this).nextAll('.<?=str_replace(' ','_',$levels[ $i + 1 ])?>Select').prop('disabled', true);
              jQuery(this).nextAll('select').each(function() {
                //jQuery(this).html('<option></option>').prop('disabled',true);
                jQuery(this).prop('disabled',true);
              });
            }
        }

其中body是jsonb列类型。

答案 2 :(得分:32)

使用Postgresql 9.5可以通过以下方式完成 -

UPDATE test
SET data = data - 'a' || '{"a":5}'
WHERE data->>'b' = '2';

OR

UPDATE test
SET data = jsonb_set(data, '{a}', '5'::jsonb);

有人问过如何一次更新jsonb值中的多个字段。假设我们创建一个表:

CREATE TABLE testjsonb ( id SERIAL PRIMARY KEY, object JSONB );

然后我们插入一个实验行:

INSERT INTO testjsonb
VALUES (DEFAULT, '{"a":"one", "b":"two", "c":{"c1":"see1","c2":"see2","c3":"see3"}}');

然后我们更新行:

UPDATE testjsonb SET object = object - 'b' || '{"a":1,"d":4}';

以下是:

  1. 更新字段
  2. 删除b字段
  3. 添加d字段
  4. 选择数据:

    SELECT jsonb_pretty(object) FROM testjsonb;
    

    将导致:

          jsonb_pretty
    -------------------------
     {                      +
         "a": 1,            +
         "c": {             +
             "c1": "see1",  +
             "c2": "see2",  +
             "c3": "see3",  +
         },                 +
         "d": 4             +
     }
    (1 row)
    

    要更新内部字段,请不要使用concat运算符||。请改用jsonb_set。这不简单:

    UPDATE testjsonb SET object =
    jsonb_set(jsonb_set(object, '{c,c1}','"seeme"'),'{c,c2}','"seehim"');
    

    使用{c,c1}的concat运算符,例如:

    UPDATE testjsonb SET object = object || '{"c":{"c1":"seedoctor"}}';
    

    将删除{c,c2}和{c,c3}。

    要获得更多权力,请在postgresql json functions documentation寻求权力。有人可能会对#-运算符,jsonb_set函数以及jsonb_insert函数感兴趣。

答案 3 :(得分:9)

为了构建@ pozs的答案,这里有一些PostgreSQL函数可能对某些人有用。 (需要PostgreSQL 9.3 +)

按键删除:按键从JSON结构中删除值。

CREATE OR REPLACE FUNCTION "json_object_del_key"(
  "json"          json,
  "key_to_del"    TEXT
)
  RETURNS json
  LANGUAGE sql
  IMMUTABLE
  STRICT
AS $function$
SELECT CASE
  WHEN ("json" -> "key_to_del") IS NULL THEN "json"
  ELSE (SELECT concat('{', string_agg(to_json("key") || ':' || "value", ','), '}')
          FROM (SELECT *
                  FROM json_each("json")
                 WHERE "key" <> "key_to_del"
               ) AS "fields")::json
END
$function$;

按键递归删除:按键路径从JSON结构中删除值。 (需要@ pozs&#39; json_object_set_key功能)

CREATE OR REPLACE FUNCTION "json_object_del_path"(
  "json"          json,
  "key_path"      TEXT[]
)
  RETURNS json
  LANGUAGE sql
  IMMUTABLE
  STRICT
AS $function$
SELECT CASE
  WHEN ("json" -> "key_path"[l] ) IS NULL THEN "json"
  ELSE
     CASE COALESCE(array_length("key_path", 1), 0)
         WHEN 0 THEN "json"
         WHEN 1 THEN "json_object_del_key"("json", "key_path"[l])
         ELSE "json_object_set_key"(
           "json",
           "key_path"[l],
           "json_object_del_path"(
             COALESCE(NULLIF(("json" -> "key_path"[l])::text, 'null'), '{}')::json,
             "key_path"[l+1:u]
           )
         )
       END
    END
  FROM array_lower("key_path", 1) l,
       array_upper("key_path", 1) u
$function$;

用法示例:

s1=# SELECT json_object_del_key ('{"hello":[7,3,1],"foo":{"mofu":"fuwa", "moe":"kyun"}}',
                                 'foo'),
            json_object_del_path('{"hello":[7,3,1],"foo":{"mofu":"fuwa", "moe":"kyun"}}',
                                 '{"foo","moe"}');

 json_object_del_key |          json_object_del_path
---------------------+-----------------------------------------
 {"hello":[7,3,1]}   | {"hello":[7,3,1],"foo":{"mofu":"fuwa"}}

答案 4 :(得分:8)

UPDATE test
SET data = data::jsonb - 'a' || '{"a":5}'::jsonb
WHERE data->>'b' = '2'

这似乎适用于PostgreSQL 9.5

答案 5 :(得分:4)

使用PostgreSQL 9.4,我们实现了以下python函数。它也可以与PostgreSQL 9.3一起使用。

create language plpython2u;

create or replace function json_set(jdata jsonb, jpaths jsonb, jvalue jsonb) returns jsonb as $$
import json

a = json.loads(jdata)
b = json.loads(jpaths)

if a.__class__.__name__ != 'dict' and a.__class__.__name__ != 'list':
  raise plpy.Error("The json data must be an object or a string.")

if b.__class__.__name__ != 'list':
   raise plpy.Error("The json path must be an array of paths to traverse.")

c = a
for i in range(0, len(b)):
  p = b[i]
  plpy.notice('p == ' + str(p))

  if i == len(b) - 1:
    c[p] = json.loads(jvalue)

  else:
    if p.__class__.__name__ == 'unicode':
      plpy.notice("Traversing '" + p + "'")
      if c.__class__.__name__ != 'dict':
        raise plpy.Error("  The value here is not a dictionary.")
      else:
        c = c[p]

    if p.__class__.__name__ == 'int':
      plpy.notice("Traversing " + str(p))
      if c.__class__.__name__ != 'list':
        raise plpy.Error("  The value here is not a list.")
      else:
        c = c[p]

    if c is None:
      break    

return json.dumps(a)
$$ language plpython2u ;

使用示例:

create table jsonb_table (jsonb_column jsonb);
insert into jsonb_table values
('{"cars":["Jaguar", {"type":"Unknown","partsList":[12, 34, 56]}, "Atom"]}');

select jsonb_column->'cars'->1->'partsList'->2, jsonb_column from jsonb_table;

update jsonb_table
set jsonb_column = json_set(jsonb_column, '["cars",1,"partsList",2]', '99');

select jsonb_column->'cars'->1->'partsList'->2, jsonb_column from jsonb_table;

请注意,对于以前的雇主,我已经为PostgreSQL 7,8和9编写了一组C函数,用于将JSON数据作为文本(而不是jsonjsonb类型)进行操作。例如,使用json_path('{"obj":[12, 34, {"num":-45.67}]}', '$.obj[2]['num']')提取数据,使用json_path_set('{"obj":[12, 34, {"num":-45.67}]}', '$.obj[2]['num']', '99.87')设置数据,依此类推。它花了大约3天的时间,所以如果你需要它在遗留系统上运行并且有时间,那么它可能是值得的。我想C版本比python版本快得多。

答案 6 :(得分:2)

我为自己编写了一个小函数,它在Postgres 9.4中以递归方式工作。这是函数(我希望它适合你):

CREATE OR REPLACE FUNCTION jsonb_update(val1 JSONB,val2 JSONB)
RETURNS JSONB AS $$
DECLARE
    result JSONB;
    v RECORD;
BEGIN
    IF jsonb_typeof(val2) = 'null'
    THEN 
        RETURN val1;
    END IF;

    result = val1;

    FOR v IN SELECT key, value FROM jsonb_each(val2) LOOP

        IF jsonb_typeof(val2->v.key) = 'object'
            THEN
                result = result || jsonb_build_object(v.key, jsonb_update(val1->v.key, val2->v.key));
            ELSE
                result = result || jsonb_build_object(v.key, v.value);
        END IF;
    END LOOP;

    RETURN result;
END;
$$ LANGUAGE plpgsql;

以下是样本使用:

select jsonb_update('{"a":{"b":{"c":{"d":5,"dd":6},"cc":1}},"aaa":5}'::jsonb, '{"a":{"b":{"c":{"d":15}}},"aa":9}'::jsonb);
                            jsonb_update                             
---------------------------------------------------------------------
 {"a": {"b": {"c": {"d": 15, "dd": 6}, "cc": 1}}, "aa": 9, "aaa": 5}
(1 row)

正如您所见,它可以深入分析并在需要时更新/添加值。

答案 7 :(得分:2)

如果您的字段类型是json,则以下内容适用于您。

UPDATE 
table_name
SET field_name = field_name::jsonb - 'key' || '{"key":new_val}' 
WHERE field_name->>'key' = 'old_value'.

运营商&#39; - &#39;从左操作数中删除键/值对或字符串元素。键/值对基于其键值进行匹配。

运营商&#39; ||&#39;将两个jsonb值连接成一个新的jsonb值。

由于这些是jsonb运算符,您只需要转换为:: jsonb

更多信息: JSON Functions and Operators

You can read my note here

答案 8 :(得分:2)

即使以下内容不能满足此请求(函数json_object_agg在PostgreSQL 9.3中不可用),以下内容对于寻找||的人来说也很有用。 PostgreSQL 9.4的运算符,在即将发布的PostgreSQL 9.5中实现:

CREATE OR REPLACE FUNCTION jsonb_merge(left JSONB, right JSONB)
RETURNS JSONB
AS $$
SELECT
  CASE WHEN jsonb_typeof($1) = 'object' AND jsonb_typeof($2) = 'object' THEN
       (SELECT json_object_agg(COALESCE(o.key, n.key), CASE WHEN n.key IS NOT NULL THEN n.value ELSE o.value END)::jsonb
        FROM jsonb_each($1) o
        FULL JOIN jsonb_each($2) n ON (n.key = o.key))
   ELSE 
     (CASE WHEN jsonb_typeof($1) = 'array' THEN LEFT($1::text, -1) ELSE '['||$1::text END ||', '||
      CASE WHEN jsonb_typeof($2) = 'array' THEN RIGHT($2::text, -1) ELSE $2::text||']' END)::jsonb
   END     
$$ LANGUAGE sql IMMUTABLE STRICT;
GRANT EXECUTE ON FUNCTION jsonb_merge(jsonb, jsonb) TO public;
CREATE OPERATOR || ( LEFTARG = jsonb, RIGHTARG = jsonb, PROCEDURE = jsonb_merge );

答案 9 :(得分:1)

可悲的是,我在文档中没有找到任何内容,但您可以使用一些解决方法,例如您可以编写一些扩展函数。

例如,在Python中:

CREATE or REPLACE FUNCTION json_update(data json, key text, value json)
returns json
as $$
from json import loads, dumps
if key is None: return data
js = loads(data)
js[key] = value
return dumps(js)
$$ language plpython3u

然后

update test set data=json_update(data, 'a', to_json(5)) where data->>'b' = '2';

答案 10 :(得分:1)

以下plpython片段可能派上用场。

CREATE EXTENSION IF NOT EXISTS plpythonu;
CREATE LANGUAGE plpythonu;

CREATE OR REPLACE FUNCTION json_update(data json, key text, value text)
 RETURNS json
 AS $$
    import json
    json_data = json.loads(data)
    json_data[key] = value
    return json.dumps(json_data, indent=4)
 $$ LANGUAGE plpythonu;

-- Check how JSON looks before updating

SELECT json_update(content::json, 'CFRDiagnosis.mod_nbs', '1')
FROM sc_server_centre_document WHERE record_id = 35 AND template = 'CFRDiagnosis';

-- Once satisfied update JSON inplace

UPDATE sc_server_centre_document SET content = json_update(content::json, 'CFRDiagnosis.mod_nbs', '1')
WHERE record_id = 35 AND template = 'CFRDiagnosis';

答案 11 :(得分:0)

你也可以在jsonb内原子地增加密钥,如下所示:

UPDATE users SET counters = counters || CONCAT('{"bar":', COALESCE(counters->>'bar','0')::int + 1, '}')::jsonb WHERE id = 1;

SELECT * FROM users;

 id |    counters
----+------------
  1 | {"bar": 1}

未定义的密钥 - &gt;假设起始值为0。

有关详细说明,请参阅我的回答:https://stackoverflow.com/a/39076637

答案 12 :(得分:0)

当我尝试更新字符串类型字段时,这对我有用。

UPDATE table_name 
SET body = jsonb_set(body, '{some_key}', to_json('value'::TEXT)::jsonb);

希望它可以帮助其他人!

答案 13 :(得分:0)

我发现先前的答案适合有经验的PostgreSQL用户,因此我的答案:

假设您有一个JSONB类型的表列,其值如下:

{
    "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"
    }
}

假设我们要在行中设置一个新值:

"key13": "*Please refer to main screen labeling"

,然后放置值:

"key13": "See main screen labeling"

我们使用json_set()函数为key13分配一个新值

jsonb_set()的参数

jsonb_set(target jsonb, path text[], new_value jsonb[, create_missing boolean])

在“ 目标”中-我将放置jsonb列名(这是正在修改的表列)

path ”-是“ json键路径”,通向(包括)我们将要覆盖的键

new_value ”-这是我们分配的新值

在我们的例子中,我们要更新位于key1(key1-> key13)下的key13的值:

因此 path语法为:'{key1,key13}' (路径是要破解的最棘手的部分-因为这些教程很糟糕)

jsonb_set(jsonb_column,'{key1,key13}','"See main screen labeling"')

答案 14 :(得分: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字符串,

答案 15 :(得分:0)

例如,我的字符串如下所示: {“ a1”:{“ a11”:“ x”,“ a22”:“ y”,“ a33”:“ z”}}

我使用临时表更新了json,对于足够少的数据量(<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与字符串有更多关系,但它可以工作。基本上,它将所有数据提取到临时表中,在使用您备份的数据插入concat漏洞的同时创建一个字符串,并将其转换为jsonb。

Json_set可能会更有效,但是我仍然对此感到困惑。第一次尝试使用它时,我完全弄乱了字符串...

答案 16 :(得分:0)

您可以尝试如下更新:

语法: UPDATE table_name SET column_name = column_name :: jsonb || '{“ key”:new_value}'列名条件;

例如:

更新测试SET数据= data :: jsonb || '{“ a”:new_value}'WHERE data->>'b'='2';

答案 17 :(得分:0)

UPDATE table_name SET attrs = jsonb_set(cast(attrs as jsonb), '{key}', '"new_value"', true) WHERE id = 'some_id';

这对我有用,attrs是一个json类型字段。首先转换为jsonb,然后更新。

UPDATE table_name SET attrs = jsonb_set(cast(attrs as jsonb), '{key}', '"new_value"', true) WHERE attrs->>key = 'old_value';

答案 18 :(得分:0)

您如何看待该解决方案?

它将添加新值或更新现有值。

编辑:进行了编辑,使其可用于空对象和空对象

Edit2:已进行编辑以使其与对象中的对象一起使用...

create or replace function updateJsonb(object1 json, object2 json)
returns jsonb
language plpgsql
as
$$
declare
    result jsonb;
    tempObj1 text;
    tempObj2 text;

begin
    tempObj1 = substr(object1::text, 2, length(object1::text) - 2); --remove the first { and last }
    tempObj2 = substr(object2::text, 2, length(object2::text) - 2); --remove the first { and last }

    IF object1::text != '{}' and object1::text != 'null' and object1::text != '[]' THEN
        result = ('{' || tempObj1 || ',' || tempObj2 || '}')::jsonb;
    ELSE
        result = ('{' || tempObj2 || '}')::jsonb;
    END IF;
    return result;
end;
$$;

用法:

update table_name
set data = updatejsonb(data, '{"test": "ok"}'::json)

答案 19 :(得分:0)

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

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

答案 20 :(得分:-2)

如果您正在使用编程语言客户端(例如来自python pycopg2Node Postgres的查询进行查询, 确保首先将新数据解析为JSON。

它很容易看起来像python字典,它与JSON对象相同,但首先不对字典进行json.dumps。

一个简单的python代码段:

def change_destination(self,parcel_id,destlatlng): query="UPDATE parcels SET destlatlng = '{}' WHERE parcel_id ={};".format(json.dumps(destlatlng), parcel_id) self.cursor.execute(query2) self.connection.commit()