我有一個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