JSON type caster

Поиск
Список
Период
Сортировка
От Tobias Oberstein
Тема JSON type caster
Дата
Msg-id 50582803.4030706@gmail.com
обсуждение исходный текст
Ответы Re: JSON type caster  (Daniele Varrazzo <daniele.varrazzo@gmail.com>)
Список 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;





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

Предыдущее
От: David Roid
Дата:
Сообщение: Re: psycopg2 hang with multithread frequent queries
Следующее
От: Daniele Varrazzo
Дата:
Сообщение: Re: JSON type caster