Ich habe eine PostgreSQL-Datenbanktabelle mit einer JSON-Datentypspalte. Wenn ich JSON-Zeichenfolgen in der Datenbank speichere, wird None
nicht beibehalten. Dies kann mit diesem Code-Schnipsel wiedergegeben werden:Python beibehalten Keine/NULL beim Speichern von JSON in Postgres
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'
Der Ausgang dieses Python-Code ist:
[email protected]:~/python$ python test.py
null
<type 'unicode'>
result is not None
[email protected]:~/python$
Wie kann ich speichern None
als Schlüssel in der JSON-Spalte? Das JSON-Objekt verfügt auch über Schlüssel für 'None'
und 'null'
, daher muss der gespeicherte Wert None
oder null
lauten.
Sie tun es falsch. Sie sollten einen [JSON * Spaltentyp * in PostgreSQL] verwenden (https://stackoverflow.com/questions/45150617/adding-dict-object-to-postgresql) ... –
Sie können nicht 'None' (oder 'null', das JSON-Äquivalent) ist ein Schlüssel in einem JSON-Objekt. Ihr Diktat ist einfach nicht mit dem JSON-Format kompatibel. – user2357112