Python通过API通过JSON提取数据,但是当尝试存储到PostgreSQL中时,我收到一条消息,字节索引必须是整数或切片,而不是字符串。
Traceback (most recent call last):
File "umbrella-import.py", line 32, in <module>
my_data = [item[field] for field in fields]
File "umbrella-import.py", line 32, in <listcomp>
my_data = [item[field] for field in fields]
TypeError: byte indices must be integers or slices, not str
我尝试将[]更改为{}。我相信这是您使用字符串创建字典的地方?我还尝试在运行cursor.execute时删除“ tuple”选项。
似乎在创建的列表和for循环之间需要更新一些内容。
response = requests.request("GET", url, data=payload, headers=headers)
connection = psycopg2.connect(user = "devops", password = "password", host = "127.0.0.1", port = "5432", database = "umbrella")
cursor = connection.cursor()
fields = [
'customerId', #Customer ID Number
'customerName', #Customer Name
]
for item in response:
my_data = [item[field] for field in fields]
insert_query = "INSERT INTO umbrelladata VALUES (%s, %s)"
cursor.execute(insert_query, tuple(my_data))
connection.commit()
cursor.close()
connection.close()
customerId是一个数字,可以存储为整数。customerName就是它所说的-客户的名字。我相信这是休息的地方吗?
在此脚本中,我试图下载客户ID号和客户名并将其存储在Postgresql数据库中。
您的JSON响应采用字节形式,当您尝试访问dict项时发生错误-
my_data = [用于字段中字段的[item [field]]]
因此,使用-将数据转换为dict
import json
response=json.loads(response)
这应该可以解决您的问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句