我有一个PostgreSQL数据库表,它具有JSON数据类型列。当我在数据库中存储JSON字符串时,None
未被保留。这可以用这个代码片段被复制:在Postgres中存储JSON时保留Python无/ NULL
import json,psycopg2
dictionary = {}
dictionary[None] = 0
conn = psycopg2.connect("host='localhost' dbname='testdb' user='postgres'
password='postgres'")
cursor = conn.cursor()
cursor.execute("""INSERT INTO testtable (json_column) VALUES (%s)""",
(json.dumps(dictionary),))
cursor.execute("""SELECT json_column FROM testtable""")
result = cursor.fetchall()[0][0].keys()[0]
print result
print type(result)
if result is None:
print 'result is None'
else:
print 'result is not None'
这个Python代码的输出是:
[email protected]:~/python$ python test.py
null
<type 'unicode'>
result is not None
[email protected]:~/python$
我如何可以存储None
作为JSON列的关键? JSON对象还具有用于'None'
和'null'
的键,因此存储的值必须是None
或null
。
你做错了。你应该在PostgreSQL中使用[JSON *列类型](https://stackoverflow.com/questions/45150617/adding-dict-object-to-postgresql)... –
你不能有'None'(或'null',JSON等价物)是JSON对象中的关键字。你的字典只是与JSON格式不兼容。 – user2357112