【发布时间】:2021-08-18 17:09:00
【问题描述】:
import psycopg2, json, requests, hidden
# Load secrets
secrets = hidden.secrets()
conn = psycopg2.connect(host=secrets['host'],port=secrets['port'],
....,connect_timeout=3)
cur = conn.cursor()
defaulturl = 'https://pokeapi.co/api/v2/pokemon?limit=100&offset=0'
sql = '''
CREATE TABLE IF NOT EXISTS pokeapi
(id INTEGER, body JSONB);
'''
print(sql)
cur.execute(sql)
response = requests.get(defaulturl)
js = json.loads(response.text)
# js is a library and i'm interested in the values of 'results' key.
results = js['results']
# 'results' is a list of libraries and i want to loop through each element of the list
# and extract the value of 'url' key
# I NEED TO INSERT EACH VALUE INTO pokeapi (body), note that 'body' is of type JSONB
for x in range(len(results)):
body = requests.get(results[x]['url'])
js_body = json.loads(body.text)
sql = f"INSERT INTO pokeapi (body) VALUES ('{js_body}')::JSONB";
cur.execute(sql, (defaulturl))
print('Closing database connection...')
conn.commit()
cur.close()
此脚本不断抛出错误:
如果不存在则创建表 pokeapi(id 整数,正文);追溯 (最近一次通话最后):文件“pokeapi.py”,第 45 行,在 cur.execute(sql, (defaulturl)) psycopg2.errors.SyntaxError: "{" LINE 1 或附近的语法错误: INSERT INTO pokeapi (body) VALUES {'abilities': [{'ability':...
我尝试插入 pokeapi (body) 而不转换为 jsonb,但我不断收到相同的错误。有没有我遗漏的基础知识?
【问题讨论】:
-
从 1) 这个
cur.execute(sql, (defaulturl))开始有些事情是没有意义的。您正在将一个参数(顺便说一句,它应该是cur.execute(sql, (defaulturl,)))传递给一个没有参数的查询sql。 2)您正在使用format,这是一个注入风险3)您没有使用pscyopg2 JSON adaptation。 -
我正在使用 psycopg2,你可能错过了顶部的导入。
-
我看到了我只是说
psycopg2有JSON适应可以节省你的步骤。 -
@AdrianKlaver 此外,不需要解析 json。只需将字符串作为参数传入即可。
-
@AndréC.Andersen,除了
js_body是json.loads的输出,因此是一个Python 对象。psycopg2.extras.Json负责为您转储,并正确引用和处理jsonb(psycopg2 2.5.4+)。如果您使用JSON工作,它非常方便。
标签: python-3.x postgresql jsonb