简体   繁体   English

Postgresql 更新 json 数据属性

[英]Postgresql update json data property

I created a field name is result and type is text.我创建了一个字段名称是结果,类型是文本。 I just want to update 'lat' in column.我只想更新列中的“lat”。 When I use this query I get syntax error.当我使用此查询时,出现语法错误。 How can I do?我能怎么做?

The column data is列数据是

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

Query is查询是

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

Syntax error is语法错误是

ERROR: syntax error at or near "::"

Use the jsonb concatenation operator ( Postgres 9.5+ ):使用jsonb 连接运算符( Postgres 9.5+ ):

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

In Postgres 9.4 use json_each() and json_object_agg() (because jsonb_object_agg() does not exists in 9.4).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

Both solutions assume that the json column is not null.两种解决方案都假定 json 列不为空。 If it does not contain the lat key, the first query will create it but the second will not.如果它不包含lat键,第一个查询将创建它,但第二个不会。

In PostgreSQL 13, You can:拨打PostgreSQL 13、您可以:

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

In case the column is still null, you can use coalesce .如果该列仍然为空,您可以使用coalesce The answer is provided here: PostgreSQL 9.5 - update doesn't work when merging NULL with JSON答案在此处提供: PostgreSQL 9.5 - 将 NULL 与 JSON 合并时更新不起作用

I also tried to update json value in json type field, but couldn't find appropriate example.我还尝试更新 json 类型字段中的 json 值,但找不到合适的示例。 So I've connected to postgres DB using PgAdmin4, opened desired table and changed desired field's value, then looked at Query History to see what command it uses to change it.所以我使用 PgAdmin4 连接到 postgres DB,打开所需的表并更改所需字段的值,然后查看查询历史以查看它使用什么命令来更改它。

So, finally, I've got the next simple python code for own purposes to update json field in postgres db:所以,最后,我有下一个简单的 python 代码,用于更新 postgres db 中的 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")

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM