JSON type caster

From: Tobias Oberstein <tobias(dot)oberstein(at)gmail(dot)com>
To: psycopg(at)postgresql(dot)org
Subject: JSON type caster
Date: 2012-09-18 07:51:31
Message-ID: 50582803.4030706@gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: psycopg

Hi,

I am adding a SQL to Python type caster for the new native JSON type in
Postgres.

This seems to work, but I wonder if it's really complete / done right
and should maybe already built into
Psycopg2 since JSON is now a native PG type.

Any comments?
Thanks,
Tobias

===
import psycopg2
import simplejson
import json
import sys

conn = psycopg2.connect(host = "127.0.0.1", port = 5434, database =
"test", user = "test", password = "xxx")
conn.autocommit = True

print conn.encoding
cur = conn.cursor()

cur.execute("SELECT null::json, null::json[]")
(json_oid, jsonarray_oid) = (cur.description[0][1], cur.description[1][1])

print json_oid, jsonarray_oid # 114 199 => are those fixed for PG or
instance specific?

def cast_json(value, cur):
if value is None:
return None
try:
#o = json.loads(value)
o = simplejson.loads(value, use_decimal = True)
return o
except:
raise InterfaceError("bad JSON representation: %r" % value)

JSON = psycopg2.extensions.new_type((json_oid,), "JSON", cast_json)
psycopg2.extensions.register_type(JSON)
psycopg2.extensions.register_type(psycopg2.extensions.new_array_type((jsonarray_oid,),
"JSON[]", JSON))

cur.execute("""SELECT now(), 23::decimal, '[23.1, {"a": "jhsd", "b": 23,
"c": [1,2,3]}]'::json, (SELECT array_agg(f1) FROM tab1), (SELECT
array_to_json(array_agg(f1)) FROM tab1)""")
r = cur.fetchone()
for i in xrange(0, len(r)):
print i, type(r[i]), r[i]

===

DROP TABLE IF EXISTS tab1;

CREATE TABLE tab1 (f1 JSON);

INSERT INTO tab1 (f1) VALUES ('"sdfs"'::json);
INSERT INTO tab1 (f1) VALUES ('[1,2,3]'::json);

SELECT * FROM tab1;

SELECT array_agg(f1) FROM tab1;

Responses

Browse psycopg by date

  From Date Subject
Next Message Daniele Varrazzo 2012-09-18 09:32:11 Re: JSON type caster
Previous Message David Roid 2012-09-18 01:59:54 Re: psycopg2 hang with multithread frequent queries