我正在将json数据插入jsonb列。当我使用python通过读取文件来执行插入操作时,数据将作为字符串插入,但是当我通过将json分配给变量(在下面注释)直接插入时,它将作为对象插入。我在下面做什么错了?
import json
import psycopg2
data = open('C:\\xx\\json\. \temp1.json').read()
my_json = json.dumps(data)
connection = psycopg2.connect(user =
"xxxxx",
password =
"xxxxx",
host = "exx",
port = "54xx",
database =
"dxxx")
cursor = connection.cursor()
insert_query = "insert into gna (data) values (%s)"
cursor.execute(insert_query, (my_json,))
connection.commit()
count = cursor.rowcount
print (count,
"Record inserted successfully into xx table")
答案 0 :(得分:0)
您逃脱了json:)
data = open('C:\\xx\\json\. \temp1.json').read()
是json字符串。您可以将其传递给postgres,只要您的文件中确实包含json字符串,就应将其解释为json。
my_json = json.dumps(data)
数据是一个字符串。如果转储字符串,则将其转义,并明确表示“这不是json对象”
import json
from io import StringIO
f = StringIO('{"key": "value"}')
data = f.read()
print(data) # {"key": "value"}
data = json.dumps(data)
print(data) # "{\"key\": \"value\"}"
data = json.dumps({"key": "value"})
print(data) # {"key": "value"}