Re: JSON type caster

From: Tobias Oberstein <tobias(dot)oberstein(at)gmail(dot)com>
To: Daniele Varrazzo <daniele(dot)varrazzo(at)gmail(dot)com>
Cc: psycopg(at)postgresql(dot)org
Subject: Re: JSON type caster
Date: 2012-09-19 12:36:11
Message-ID: 5059BC3B.90402@gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: psycopg

Great!!

> I've implemented the Json adapter and the register_json function: they
> are available in the "json" branch in my repository:
> <https://github.com/dvarrazzo/psycopg/tree/json>. For PG 9.2 calling
> register_json() is not required.
>
> The docs are not online as still not complete; what is available can
> be read generating the docs locally (make docs) or peeking at the
> docstrings in _json.py
> <https://github.com/dvarrazzo/psycopg/blob/json/lib/_json.py>
>
> Comments and tests are appreciated.

I have tested the branch on FreeBSD 9 STABLE amd64 and PG 9.2. Works
flawlessly .. everything as expected.

The

psycopg2.extensions.register_adapter(dict, psycopg2.extras.Json)

feature is nifty!

A minor inconvenience: when on PG 9.2 OIDs are well know, but when
I need to register a custom JSON typecaster, I nevertheless need
to supply the OIDs _or_ provide a connection (which I may want
to avoid when I want the behavior globally):

loads = lambda x: json.loads(x, parse_float = Decimal)
psycopg2.extras.register_json(None, globally = True, loads = loads, oid
= 114, array_oid = 199)
#psycopg2.extras.register_json(None, globally = True, loads = loads) #
won't work

I am fine with that, but the example in the docs would probably profit
from mentioning this code snippet .. "how to install custom JSON
typecaster on PG92 globally".

Another thing that's probably inconvenient: psycopg2.extras.Json
forwards kwargs for customization, but there is no trivial way
of using a different "json" implementation altogether like i.e.

simplejson (which has features not in Py json even for 2.7 like
use_decimal .. which works correctly without any rounding)

ujson (which claims to be the fastes Py json anyway)

How about:

class Json(object):

def __init__(self, adapted, **kwargs):
self.adapted = adapted
self.kwargs = kwargs

def dumps(self, o, **kwargs):
return json.dumps(o, **kwargs)

def __conform__(self, proto):
if proto is ISQLQuote:
return self

def getquoted(self):
s = self.dumps(self.adapted, **self.kwargs)
return QuotedString(s).getquoted()

class CustomJson(Json):
def dumps(self, o, **kwargs):
return simplejson.dumps(o, **kwargs)

==

So there is no need to reimplement getquoted (which may do Psycopg
implementation details)..

Cheers,
Tobias

>
> -- Daniele
>

In response to

Responses

Browse psycopg by date

  From Date Subject
Next Message Daniele Varrazzo 2012-09-19 13:12:56 Re: JSON type caster
Previous Message Federico Di Gregorio 2012-09-19 07:31:20 Re: Problem with Zope 2.13.15, python 2.6.6 psycopg2-2.4.5, pg 9.0.3