Re: Problem with the default registration of the JSON adapter

Поиск
Список
Период
Сортировка
От Daniele Varrazzo
Тема Re: Problem with the default registration of the JSON adapter
Дата
Msg-id CA+mi_8Y6QE49dTrg9fAdhFAz57BvvSh_2kdA=5otW8-eMd6ckg@mail.gmail.com
обсуждение исходный текст
Ответ на Re: Problem with the default registration of the JSON adapter  (Christophe Pettus <xof@thebuild.com>)
Список psycopg
On Mon, Jul 22, 2013 at 5:13 PM, Christophe Pettus <xof@thebuild.com> wrote:
>
> On Jul 22, 2013, at 9:06 AM, Federico Di Gregorio wrote:
>
>> Looking forward, I'd say that if a type has only one useful
>> representation, that one should be used; but if it has multiple useful
>> representations the *simplest* one should be the default.
>
> I have to say that I find the current situation pleasing: psycopg2 does the most natural thing with the type
(convertsit to a data structure, which is after all what json is encoding) if you ask for the base type.  If you want
thetext version, just cast it to the text version in the query, and that's what you get, parallel with every other
type.

I've been thinking about this issue for a while, and I think too I
like what we do better than the alternatives. Without assumption of
what people does or doesn't do with their data, JSON is structured
data and getting it in structured way in Python is a sensible default.

    >>> cur.execute("""select '{"data": "here", "more": [1,2,3]}'::json""")
    >>> cur.fetchone()[0]
    {u'data': u'here', u'more': [1, 2, 3]}

It's just as natural as this: json is structure and we get a
reasonable structure by default, with plenty of customization
possibilities if the defaults are not right for the task. If somebody
doesn't want the structured data but just a string to pass through,
querying json as text is a perfect workaround, requiring no knowledge
of psycopg internals. The best workaround in psycopg is probably not
to unregister the adapter as suggested in the first thread message,
but to register the text (or unicode) adapter on the json oids, which
can be done at smaller scope than globally and doesn't leak the
string_types implementation:

    ext.register_type(ext.new_type(ext.JSON.values, 'JSON2STR',
psycopg2.STRING))

I would mention this in the docs but leave the json handling as it is.
For future data types we will discuss whether handling them by default
would be wise or not.

-- Daniele


В списке psycopg по дате отправления:

Предыдущее
От: Daniele Varrazzo
Дата:
Сообщение: Re: Fw: Problem with psycopg2, bytea, and memoryview
Следующее
От: Wenceslao Grillo
Дата:
Сообщение: Unwanted debug messages