python - 如何使用python将json文件插入postgresql数据库?
问题描述
python代码: 如您所见,我编写了代码,我的代码有问题,请帮助我
import requests
import json
import psycopg2
import urllib
from urllib.request import Request, urlopen
con = psycopg2.connect(database='test', user='postgres', password='affan@123', host='localhost', port='5432')
cursor = con.cursor()
url = 'https://api.imgflip.com/get_memes'
page=urllib.request.Request(url,headers={'User-Agent': 'chrome'})
response = urllib.request.urlopen(page).read()
json_obj = str(response, 'utf-8')
json_obj = json.loads(response.decode('utf-8'))
cursor.execute(
"""create table if not exists memes_data(
id text, name text, url text, width integer, height integer, box_count integer);"""
)
for obj in json_obj:
print(obj["id"])
print(obj["name"])
print(obj["url"])
print(obj["width"])
print(obj["height"])
print(obj["box_count"])
cursor.execute("INSERT INTO memes_data (id, name, url, width, height, box_count) VALUES (%s,%s,%s,%s,%s,%s)", (obj["id"], obj["name"], obj["url"], obj["width"], obj["height"], obj["box_count"]))
con.commit()
con.close()
运行时 出现错误,您看到字符串索引必须是整数,我该怎么办?
Traceback (most recent call last):
File "c:\Users\shaik\Desktop\api ex\ob.py", line 22, in <module>
print(obj["id"])
TypeError: string indices must be integers
解决方案
您的代码中的某些行是不必要的。例如,您要声明 json_obj 两次。只有第二个给你一本字典。此外,您导入请求但不使用它。
获取 JSON 对象/字典的部分可以简化为:
from urllib.request import Request, urlopen
url = 'https://api.imgflip.com/get_memes'
page = Request(url, headers={'User-Agent': 'chrome'})
response = urlopen(page).read()
json_obj = json.loads(response.decode('utf-8'))
现在你想迭代你的 json_obj 中的模因。您需要声明要迭代的列表的确切路径:
memes = json_obj["data"]["memes"]
for obj in memes:
print(obj["id"])
print(obj["name"])
print(obj["url"])
print(obj["width"])
print(obj["height"])
print(obj["box_count"])
推荐阅读
- sql - 使用 MERGE 语句时语法不正确
- python - FizzBuzz 还打印包含 3 和 5 的数字
- perl - 使用 DateTime 在 Perl 中显示 12 小时制时间
- r - 根据 Shiny R 中的单选按钮选择过滤列
- html - 如何传递图像下的文本,其中两列在引导程序上定义为图像,另一列用于文本?
- ios - 有人可以在发布图片时帮助我解决一个奇怪的 firebase 错误吗?
- chisel - makeSink 方法为外围设备制作 IO 的目的是什么
- python-3.x - 从文本条目返回值到其他类
- python - 为什么sk学习中的k-fold不打印数组值
- ros - GazeboRosControlPlugin 缺失