python - ** 之后的类型对象参数必须是映射,而不是 str
问题描述
我想从站点获取 json 并将其更改为 python 对象。我写了这段代码,但它向我显示了这个错误:
----- line 25, in <module>
meme_list.append(meme(**u))
TypeError: type object argument after ** must be a mapping, not str
这是我的代码:
import requests
import json
url = 'https://api.imgflip.com/get_memes'
headers = {'Accept': 'application/json'}
response = requests.get(url, headers=headers)
with open('meme_imgflip.json', 'wb') as outf:
outf.write(response.content)
class meme:
def __init__(self, name, url, id):
self.name = name
self.url = url
self.id = id
@staticmethod
def from_json(meme_string):
return meme(**json_dict)
def __repr__(self):
return f'<meme {self.id}>'
meme_list = []
with open('meme_imgflip.json', 'r') as json_file:
meme_data = json.loads(json_file.read())
for u in meme_data:
meme_list.append(meme(**u))
print (meme_list)
解决方案
您调用的 API 返回字典,而不是列表。模因列表位于meme_data['data']['memes']
. 所以循环应该是:
for u in meme_data['data']['memes']:
meme_list.append(meme(**u))
推荐阅读
- swift - Firebase Auth: user profile changes are not synced to other devices?
- google-cloud-dataflow - 将 avro 文件导入 Bigtable - 找不到家庭错误
- r - 为什么 Flowcore 包中的函数 Write.fcs 会损坏我的 FCS 文件
- php - php无法创建用户
- angular - Asp.Net Core MVC(2.2 版):添加 Angular 7 应用程序
- javascript - Multer前端的自定义文件名
- angular - How to invoke angular component tests from protractor?
- date - 无法将双精度列表格式化为日期类型
- android - 我正在尝试在 kotlin 中实现导航抽屉,但出现错误
- firebase - Firebase Error: Auth error from APNS or Web Push Service