register_adapter Json with custom JSONEncoder

From: Hans Ginzel <hans(at)matfyz(dot)cz>
To: psycopg(at)lists(dot)postgresql(dot)org
Subject: register_adapter Json with custom JSONEncoder
Date: 2020-07-13 15:49:07
Message-ID: 20200713154907.GH81733@artax.karlin.mff.cuni.cz
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: psycopg

Hello,

how can I register an adapter with custom JSONEncoder, please.

On Stack Overflow, https://stackoverflow.com/a/55939024/2556118
I have found to use Json class
psycopg2.extensions.register_adapter(dict, psycopg2.extras.Json).

But I need to use custom JSONEncoder because of bson.ObectId type
# https://stackoverflow.com/a/16586277/2556118
import json
from bson import ObjectId
class JSONEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, ObjectId):
return str(o)
return supper().JSONEncoder.default(self, o)

There is a parameter dumps in Json.__init__(self, adapted, dumps=None),
but how to set it when used with register_adapter(),
https://www.psycopg.org/docs/extensions.html#psycopg2.extensions.register_adapter?

Should I write myself the whole Json class?

Thank you in advance,
Hans

Responses

Browse psycopg by date

  From Date Subject
Next Message Daniele Varrazzo 2020-07-13 16:15:19 Re: register_adapter Json with custom JSONEncoder
Previous Message Adrian Klaver 2020-05-28 16:47:44 Re: Async notifications in psycopg3