返回 postgres 查询时 Psycopg2 无效 json

Psycopg2 invalid json when returning postgres query

我正在使用 Django 访问我的 postgres 数据库中的存储函数。当我在 Postgres 中执行函数时,它 returns 双引号并且有效 json。但是,当我从 Django(使用 psycopg2)调用该函数时,双引号被删除并被单引号替换。

似乎 psycopg2 正在后台对列表/字典进行某种类型的转换。但是,我需要保留 json。有什么解决办法吗?

您可以通过使用 register_default_json()

注册空操作函数来覆盖 psycopg2 自动转换 JSON object/array 的功能
psycopg2.extras.register_default_json(loads=lambda x: x)

引自文档

Psycopg automatically converts PostgreSQL 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 register_default_json():

psycopg2.extras.register_default_json(loads=lambda x: x) See JSON adaptation for further details.

补充阅读