使用包含单引号的 json 更新 PostgreSQL 中的 jsonb 字段
Update jsonb field in PostgreSQL with json that contains single quote
我正在使用 PostgreSQL v9.4.12 并且正在尝试更新 jsonb 列。我想更新整个 json 对象而不是对象的特定键。
我正在使用 Python dict
来存储我的对象,在使用它之前,我正在使用 json.dumps()
将其转换为 json 格式的字符串。
但是,json 的值有一个单引号 '
,在尝试更新时抛出 psycopg2.ProgrammingError: syntax error
。
到目前为止,我已经尝试过:
"UPDATE table "
"SET jsonb_column='{} ".format(json.dumps(new_data)) + ""
"WHERE id='12345'"
请注意,new_data
是我的字典,jsonb_column
是保存 json 数据的列的名称。
我遇到的错误:
psycopg2.ProgrammingError: syntax error at or near "s"
LINE 1: ...code": "BR3", "short_description": "This property's price
is...
^
我假设 json.dumps()
转义了单引号,但似乎并非如此。有解决这个错误的方法吗?
提前致谢。
json 用单引号很好,例如:
t=# select $${"short_description": "This property's price is..."}$$::jsonb;
jsonb
------------------------------------------------------
{"short_description": "This property's price is..."}
(1 row)
所以我假设您可以尝试使用美元符号引号,以避免使用单引号的语句结构异常
字符串连接的做法不是一个好的做法。
最好使用documented in PsyCoPg2 docs.
的方式
cur.execute("UPDATE table SET jsonb_column = %s WHERE id = %s", [json, id])
我正在使用 PostgreSQL v9.4.12 并且正在尝试更新 jsonb 列。我想更新整个 json 对象而不是对象的特定键。
我正在使用 Python dict
来存储我的对象,在使用它之前,我正在使用 json.dumps()
将其转换为 json 格式的字符串。
但是,json 的值有一个单引号 '
,在尝试更新时抛出 psycopg2.ProgrammingError: syntax error
。
到目前为止,我已经尝试过:
"UPDATE table "
"SET jsonb_column='{} ".format(json.dumps(new_data)) + ""
"WHERE id='12345'"
请注意,new_data
是我的字典,jsonb_column
是保存 json 数据的列的名称。
我遇到的错误:
psycopg2.ProgrammingError: syntax error at or near "s"
LINE 1: ...code": "BR3", "short_description": "This property's price is...
^
我假设 json.dumps()
转义了单引号,但似乎并非如此。有解决这个错误的方法吗?
提前致谢。
json 用单引号很好,例如:
t=# select $${"short_description": "This property's price is..."}$$::jsonb;
jsonb
------------------------------------------------------
{"short_description": "This property's price is..."}
(1 row)
所以我假设您可以尝试使用美元符号引号,以避免使用单引号的语句结构异常
字符串连接的做法不是一个好的做法。
最好使用documented in PsyCoPg2 docs.
的方式cur.execute("UPDATE table SET jsonb_column = %s WHERE id = %s", [json, id])