Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1jxTp3-0006fH-K8 for psycopg@arkaria.postgresql.org; Mon, 20 Jul 2020 11:19:05 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1jxTp0-0000Te-Tp for psycopg@arkaria.postgresql.org; Mon, 20 Jul 2020 11:19:02 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1jxTp0-0000TV-Oc for psycopg@lists.postgresql.org; Mon, 20 Jul 2020 11:19:02 +0000 Received: from postak.karlin.mff.cuni.cz ([195.113.30.11]) by magus.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1jxTow-0003rY-Dq for psycopg@lists.postgresql.org; Mon, 20 Jul 2020 11:19:00 +0000 Received: from artax.karlin.mff.cuni.cz (artax.karlin.mff.cuni.cz [195.113.26.195]) by postak.karlin.mff.cuni.cz (Postfix) with ESMTPS id 56E0E201DA for ; Mon, 20 Jul 2020 13:18:55 +0200 (CEST) Received: by artax.karlin.mff.cuni.cz (Postfix, from userid 1975) id 3BEF7828001; Mon, 20 Jul 2020 13:18:55 +0200 (CEST) Date: Mon, 20 Jul 2020 13:18:55 +0200 From: Hans Ginzel To: psycopg@lists.postgresql.org Subject: Re: register_adapter Json with custom JSONEncoder Message-ID: <20200720111854.GA63808@artax.karlin.mff.cuni.cz> Mail-Followup-To: psycopg@lists.postgresql.org References: <20200713154907.GH81733@artax.karlin.mff.cuni.cz> MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii; format=flowed Content-Disposition: inline In-Reply-To: User-Agent: Mutt/1.5.21 (2010-09-15) List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk On Mon, Jul 13, 2020 at 05:15:19PM +0100, Daniele Varrazzo wrote: >You can use a partial function for instance, of the like of: `lambda >obj: Json(obj, dumps=mydumps)`. Thank you, Daniele. I have (succesfully) tried from psycopg2.extras import Json from json import JSONEncoder from bson import ObjectId class JSONEncoder(JSONEncoder): def default(self, o): if isinstance(o, ObjectId): return str(o) return supper().default(self, o) jsonEncoder = JSONEncoder() #psycopg2.extensions.register_adapter(dict, Json) psycopg2.extensions.register_adapter(dict, lambda o: Json(o, dumps=jsonEncoder.encode)) and variants like import json psycopg2.extensions.register_adapter(dict, lambda o: Json(o, dumps = lambda oo: json.dumps(oo, default=str))) or from bson import json_util psycopg2.extensions.register_adapter(dict, lambda o: Json(o, dumps=json_util.dumps)) I choosed the first one because of cached Encoder and cleanest way. Best regards, Hans