如何更新存储在 PostgreSQL 文本字段中的 json 数据?

Bri*_*ian 4 postgresql json

我有一个表services,其中有一列名为 ,properties其类型为text

列中存储有json数据properties

我可以这样查询json数据:psql

SELECT * FROM services WHERE properties::json->>'url' = 'www.example.com';
Run Code Online (Sandbox Code Playgroud)

但我无法json使用以下查询更新数据:

UPDATE 
   services SET properties::json->>'url' = 'www.mydomain.com' 
WHERE 
   properties::json->>'url' = 'www.example.com';
Run Code Online (Sandbox Code Playgroud)

上面的命令UPDATE会生成错误:

ERROR:  syntax error at or near "::"
LINE 1: UPDATE services SET properties::json->>'url' = 'www.....
Run Code Online (Sandbox Code Playgroud)

如何更新列url内的字段properties

UPDATE我的命令有什么问题吗?

Kau*_*yak 5

您应该将记录存储为JSONTEXT不是在所有地方都不需要类型转换。

如果您运行的是 Postgres 9.5+,您可以使用jsonb_set

UPDATE 
   services SET properties = jsonb_set(properties::jsonb,
                 '{url}' , '"www.mydomain.com"' )::text
WHERE 
   properties::json->>'url' = 'www.example.com';
Run Code Online (Sandbox Code Playgroud)

演示