Re: register_adapter Json with custom JSONEncoder

From: Daniele Varrazzo <daniele(dot)varrazzo(at)gmail(dot)com>
To: Hans Ginzel <hans(at)matfyz(dot)cz>
Cc: psycopg(at)lists(dot)postgresql(dot)org
Subject: Re: register_adapter Json with custom JSONEncoder
Date: 2020-07-13 16:15:19
Message-ID: CA+mi_8bPLhcgA3KgyZ-g+=oSkUBjaB-JoZD5oAKVjPqbm8iiog@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: psycopg

Hello,

On Mon, 13 Jul 2020 at 16:49, Hans Ginzel <hans(at)matfyz(dot)cz> wrote:
[...]

> But I need to use custom JSONEncoder because of bson.ObectId type
> # https://stackoverflow.com/a/16586277/2556118

This doc page has more examples:
https://www.psycopg.org/docs/extras.html#json-adaptation

> There is a parameter dumps in Json.__init__(self, adapted, dumps=None),
> but how to set it when used with register_adapter(),

You can use a partial function for instance, of the like of: `lambda
obj: Json(obj, dumps=mydumps)`.

> https://www.psycopg.org/docs/extensions.html#psycopg2.extensions.register_adapter?
>
> Should I write myself the whole Json class?

No, if you really want you can subclass the one we provide and only
override `_dumps()`: the one psycopg2 provides consists in pretty
much:

class Json(object):
def __init__(self, adapted, dumps=None):
self.adapted = adapted
self._dumps = dumps or json.dumps

def dumps(self, obj):
return self._dumps(obj)

so you can either create your instances using a wrapper in
register_adapter, or subclass the _dumps() method of the class: as you
can see it is equivalent. I guess the first method is better as you
don't need to care about the implementation of the `Json` class.

-- Daniele

In response to

Responses

Browse psycopg by date

  From Date Subject
Next Message Hans Ginzel 2020-07-20 11:18:55 Re: register_adapter Json with custom JSONEncoder
Previous Message Hans Ginzel 2020-07-13 15:49:07 register_adapter Json with custom JSONEncoder