首页 > 解决方案 > ** 之后的类型对象参数必须是映射,而不是 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)

标签: python

解决方案


您调用的 API 返回字典,而不是列表。模因列表位于meme_data['data']['memes']. 所以循环应该是:

for u in meme_data['data']['memes']:
    meme_list.append(meme(**u))

推荐阅读