2017-08-04 28 views
1

我有一個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'的鍵,因此存儲的值必須是Nonenull

+0

你做錯了。你應該在PostgreSQL中使用[JSON *列類型](https://stackoverflow.com/questions/45150617/adding-dict-object-to-postgresql)... –

+0

你不能有'None'(或'null',JSON等價物)是JSON對象中的關鍵字。你的字典只是與JSON格式不兼容。 – user2357112

回答

2

RFC 7159

一個目的結構被表示爲一對大括號 的周邊零個或多個名稱/值對(或成員)。 名稱是 字符串。

而且從Python docs

鍵在鍵/ JSON的值對類型STR的始終。 當 字典轉換爲JSON時,字典中的所有鍵都被強制爲字符串 。

JSON 沒有非字符串字典鍵的任何概念。如果你想要這些,你不需要JSON。您用JSON得到的最接近的值是檢測到字符串None被轉換爲並希望您永遠不需要實際使用字符串'null'作爲字典鍵。

+0

是否有另外一種可處理非字符串鍵的類似字典的數據類型? – Drew

+0

@德魯:您可能對[YAML]感興趣(https://en.wikipedia.org/wiki/YAML)。 – user2357112