python - 将字符串输入 PostgreSQL 会导致单引号语法错误

标签 python json postgresql syntax-error psycopg2

我正在运行一个非常大的数据集,每行都有一个 json 对象。在处理了近 10 亿行之后,我的事务突然出现错误。

我正在使用 Python 3.x 和 psycopg2 来执行我的交易。

我尝试编写的json对象如下:

{"message": "ConfigManager: Config if valid JSON but doesn't seem to have the correct schema. Adopting new config aborted."}

psycopg2 报告以下内容:

syntax error at or near "t"
LINE 3: ...": "ConfigManager: Config if valid JSON but doesn't seem to ...

我知道问题出在单引号上,但是我不知道如何避免这个问题,以便将 json 对象传递到我的数据库。

我的 json 列的类型为 jsonb,名为 first_row

所以如果我尝试:

INSERT INTO "356002062376054" (first_row) VALUES {"message": "ConfigManager: Config if valid JSON but doesn't seem to have the correct schema. Adopting new config aborted."}

我仍然收到错误。我似乎所做的一切都无法解决这个问题。我尝试使用 \ 转义 t 并将双引号更改为单引号,并删除大括号。没有任何效果。

我相信我记得做的事情非常重要

`json.dumps({"message": "ConfigManager: Config if valid JSON but doesn't seem to have the correct schema. Adopting new config aborted."})` in my python code and yet I am getting this problem.

最佳答案

为此,您可以使用美元符号约束或 C 样式转义。例如每docs :

An escape string constant is specified by writing the letter E (upper or lower case) just before the opening single quote, e.g., E'foo'

那么:

INSERT INTO "356002062376054" (first_row) SELECT e'{"message": "ConfigManager: Config if valid JSON but doesn\'t seem to have the correct schema. Adopting new config aborted."}'

INSERT INTO "356002062376054" (first_row) values (E'{"message": "ConfigManager: Config if valid JSON but doesn\'t seem to have the correct schema. Adopting new config aborted."}');

应该适合你

关于python - 将字符串输入 PostgreSQL 会导致单引号语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41954262/

相关文章:

python - 在 Python 中为 os.path.expandpath 使用自定义环境变量

python - 将一个整数范围以指数方式转换为另一个范围

json - Flutter - 如何将嵌套的 json 解析为具有泛型的类?

json - 如何使用 jq 将字段与通配符匹配?

java - 我如何使用 java、RestAssured 测试 Web 服务自动替换 Json 对象文件中的两个单独的 ID

PostgreSQL : How to join with multiple cross-reference table?

postgresql - 创建一个带有参数作为子选择的函数

Python:当父进程死亡时如何杀死子进程?

python - Codility - 使用 Python 进行磁带平衡训练

postgresql - PostgreSQL 上所有列的索引