Re: Problem with the default registration of the JSON adapter

From: Daniele Varrazzo <daniele(dot)varrazzo(at)gmail(dot)com>
To: Christophe Pettus <xof(at)thebuild(dot)com>
Cc: Federico Di Gregorio <federico(dot)digregorio(at)dndg(dot)it>, "psycopg(at)postgresql(dot)org" <psycopg(at)postgresql(dot)org>
Subject: Re: Problem with the default registration of the JSON adapter
Date: 2013-08-01 15:45:03
Message-ID: CA+mi_8Y6QE49dTrg9fAdhFAz57BvvSh_2kdA=5otW8-eMd6ckg@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: psycopg

On Mon, Jul 22, 2013 at 5:13 PM, Christophe Pettus <xof(at)thebuild(dot)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 (converts it to a data structure, which is after all what json is encoding) if you ask for the base type. If you want the text 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

In response to

Browse psycopg by date

  From Date Subject
Next Message Wenceslao Grillo 2013-08-05 18:05:34 Unwanted debug messages
Previous Message Daniele Varrazzo 2013-08-01 13:44:43 Re: Fw: Problem with psycopg2, bytea, and memoryview