Added doc notes about how to avoid JSON parsing

Added FAQ too as it has bitten more than one user
(see tickets #172, #190).
This commit is contained in:
Daniele Varrazzo 2014-01-14 18:30:41 +00:00
parent 3f6497d587
commit 9e8923b884
2 changed files with 27 additions and 1 deletions

View File

@ -189,6 +189,20 @@ the `Json` adapter::
Reading from the database, |pgjson| values will be automatically converted to
Python objects.
.. note::
If you are using the PostgreSQL :sql:`json` data type but you want to read
it as string in Python instead of having it parsed, your can either cast
the column to :sql:`text` in the query (it is an efficient operation, that
doesn't involve a copy)::
cur.execute("select jsondata::text from mytable")
or you can register a no-op `!loads()` function with
`register_default_json()`::
psycopg2.extras.register_default_json(loads=lambda x: x)
.. note::
You can use `~psycopg2.extensions.register_adapter()` to adapt any Python
@ -204,7 +218,7 @@ Python objects.
effects.
If you want to customize the adaptation from Python to PostgreSQL you can
either provide a custom `!dumps()` function to `!Json`::
either provide a custom `!dumps()` function to `Json`::
curs.execute("insert into mytable (jsondata) values (%s)",
[Json({'a': 100}, dumps=simplejson.dumps)])

View File

@ -125,6 +125,18 @@ Psycopg converts :sql:`decimal`\/\ :sql:`numeric` database types into Python `!D
`!psycopg2._psycopg.DECIMAL` instead.
.. _faq-json-adapt:
.. cssclass:: faq
Psycopg automatically converts PostgreSQL :sql:`json` data into Python objects. How can I receive strings instead?
The easiest way to avoid JSON parsing is to register a no-op function with
`~psycopg2.extras.register_default_json()`::
psycopg2.extras.register_default_json(loads=lambda x: x)
See :ref:`adapt-json` for further details.
.. _faq-bytea-9.0:
.. cssclass:: faq