-
The psycopg json default adapter always calls the I wonder if sql NULL is the better default way to handle |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
If you want a None to be transformed into NULL, one possibility is to keep it out of the Json wrapper at application time, e.g. cursor.execute("INSERT INTO jsondata VALUES (%s)", [Json(obj) if obj is not None else None])`). You can also customize the json dump method yourself as described in the docs. For instance (untested): class MyJson(Json):
def dumps(self, obj):
return super().dumps(obj) if obj is not None else "NULL"
curs.execute("insert into mytable (jsondata) values (%s)",
[MyJson({'a': 100})]) This is probably valid in the context of your application, but not suitable as a default in psycopg2, and wouldn't work in psycopg 3 (as explained below). As psycopg is a driver, its aim is to provide a complete mechanism to cover the entire data domain. Different applications may have different needs and I don't think that everyone would be happy with a transformation
The latter also makes hard and inefficient to use server-side binding with |
Beta Was this translation helpful? Give feedback.
Json
is a wrapper, not an adapter, and it suggests the adaptation mechanism "this object is to be dumped as json". it sounds like you are adaptingJson(None)
, which would be probably transformed into a'null'::json
. If you dump aNone
it will be dumped asNULL
.If you want a None to be transformed into NULL, one possibility is to keep it out of the Json wrapper at application time, e.g.
You can also customize the json dump method yourself as described in the docs. For instance (untested):