我希望将python数据结构作为json存储在Postgresql数据库中。
json.dumps()运行良好,我得到了一个格式正确的JSON,如下所示:
>>> import json
>>> j = { 'table': '"public"."client"' }
>>> json.dumps(j)
'{"table": "\\"public\\".\\"client\\""}'如果我执行print(json.dumps(j)),则只打印一个反斜杠,因为它被Python用作转义字符,如下所示:
>>> import json
>>> j = { 'table': '"public"."client"' }
>>> json.dumps(j)
'{"table": "\\"public\\".\\"client\\""}'
>>> print(json.dumps(j))
{"table": "\"public\".\"client\""}问题所在
当我尝试用psycopg2 ( 反斜杠不应被剥去 )将这个json存储在Postgresql上时,我想。
import psycopg2
import json
try:
conn = psycopg2.connect("service=geotuga")
cursor = conn.cursor()
j = { 'table': '"public"."client"' }
cursor.execute("INSERT INTO users.logger(subject,detail) VALUES (%s, %s);", ('json',json.dumps(j) ))
conn.commit()
cursor.close()
except (Exception, psycopg2.Error) as e:
print(e)
finally:
if conn is not None:
conn.close()在数据库中,json字符串存储为:{"table": "\"public\".\"client\""}。双反斜杠消失了。
如何在不松开双反斜杠的情况下正确地存储由json.dumps 和 psycopg2 创建的JSON?
注意:存储在数据库中的json不再有效。例如,如果我试图用Javascript解析它,它就失败了:
> x = '{"table": "\"public\".\"client\""}'
'{"table": ""public"."client""}'
> JSON.parse(x)
SyntaxError: Unexpected token p in JSON at position 12发布于 2019-12-03 23:54:52
正如luigibertaco所指出的,问题在于我如何观察数据库中的数据。使用psycopg2.将双反斜杠正确地写入数据库。
如果我这样做了:
# select detail from users.logger where subject = 'json' limit 1;
detail
------------------------------------
{"table": "\"public\".\"client\""}
(1 row)输出只显示一个斜杠。
但是,如果我使用quote_literal Postgresql函数,就会得到原始数据:
# select quote_literal(detail) from users.logger where subject = 'json' limit 1;
quote_literal
-------------------------------------------
E'{"table": "\\"public\\".\\"client\\""}'
(1 row)Postgresql能够解析字符串。
我做过的另一个检查是在Postgresql端测试json解析。它可以工作,所以字符串是正确编码的。
# select detail::json->'table' from users.logger where subject = 'json' limit 1;
?column?
-------------------------
"\"public\".\"client\""
(1 row)https://stackoverflow.com/questions/59148712
复制相似问题