diff --git a/doc/src/extras.rst b/doc/src/extras.rst index 66369abd..a0a2d1ca 100644 --- a/doc/src/extras.rst +++ b/doc/src/extras.rst @@ -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)]) diff --git a/doc/src/faq.rst b/doc/src/faq.rst index 00f9be3a..fe675231 100644 --- a/doc/src/faq.rst +++ b/doc/src/faq.rst @@ -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