Postgresql 更新 json 数据 属性

Postgresql update json data property

我创建了一个字段名是结果,类型是文本。我只想更新列中的 'lat'。当我使用此查询时,出现语法错误。我能怎么做?

列数据为

"{"lat":"48.00855","lng":"58.97342","referer":"https:\/\/abc.com\/index.php"}"

查询是

update public.log set (result::json)->>'lat'=123 where id=6848202

语法错误

ERROR:  syntax error at or near "::"

使用jsonb concatenation operatorPostgres 9.5+):

update log
set result = result::jsonb || '{"lat":"123"}'
where id = 6848202

Postgres 9.4中使用json_each()json_object_agg()(因为jsonb_object_agg()在9.4中不存在)。

update log
set result = (
    select json_object_agg(key, case key when 'lat' then '123' else value end)
    from json_each(result)
    )
where id = 6848202

两种解决方案都假定 json 列不为空。如果它不包含 lat 键,第一个查询将创建它,但第二个查询不会。

如果该列仍然为空,您可以使用 coalesce。答案在这里提供:

我也尝试更新 json 类型字段中的 json 值,但找不到合适的示例。所以我使用 PgAdmin4 连接到 postgres 数据库,打开所需的 table 并更改所需字段的值,然后查看 查询历史记录 以查看它使用什么命令来更改它。

所以,最后,我得到了下一个简单的 python 代码,用于更新 postgres 数据库中的 json 字段:

import psycopg2

conn = psycopg2.connect(host='localhost', dbname='mydbname', user='myusername', password='mypass', port='5432')
cur = conn.cursor()
cur.execute("UPDATE public.mytable SET options = '{\"credentials\": \"required\", \"users\": [{\"name\": \"user1\", \"type\": \"string\"}]}'::json WHERE id = 8;")
cur.execute("COMMIT")

在 PostgreSQL 13 中,您可以:

update public.log set result = jsonb_set(result,'{lat}','"123"') where id=6848202;