Skip to content

json adapter None conversion #1433

Answered by dvarrazzo
jerch asked this question in Q&A
Mar 14, 2022 · 1 comments · 1 reply
Discussion options

You must be logged in to vote

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 adapting Json(None), which would be probably transformed into a 'null'::json. If you dump a None it will be dumped as NULL.

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 "N…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@jerch
Comment options

Answer selected by jerch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants