首页 > 解决方案 > 如何使用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

标签: pythonjsonpostgresqlinsert

解决方案


您的代码中的某些行是不必要的。例如,您要声明 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"])

推荐阅读