我正在使用 Django 应用程序中的请求进行 API 调用。我不断收到关于名称的关键错误。 json 响应非常大,所以我只选择某些字段来使用。但错误出现在 json 列表中的第一项上。
json 的前几行看起来像这样,
"cards": [
{
"name": "Air Elemental",
"manaCost": "{3}{U}{U}",
"cmc": 5,
"colors": [
"Blue"
],
"type": "Creature — Elemental",
"types": [
"Creature"
],
"subtypes": [
"Elemental"
],
在我看来,我正在像这样解析 json,
def graphs(request):
if request.user.is_authenticated():
parsedData = []
req = requests.get('https://api.magicthegathering.io/v1/cards')
jsonList = []
jsonList.append(json.loads(req.content.decode()))
cardData = {}
for cards in jsonList:
cardData['name'] = cards['name']
cardData['manaCost'] = cards['manaCost']
cardData['colors'] = cards['colors']
cardData['type'] = cards['type']
cardData['rarity'] = cards['rarity']
cardData['set'] = cards['set']
cardData['text'] = cards['text']
cardData['flavor'] = cards['flavor']
cardData['artist'] = cards['artist']
cardData['power'] = cards['power']
cardData['toughness'] = cards['toughness']
cardData['layout'] = cards['layout']
cardData['multiverseid'] = cards['multiverseid']
cardData['id'] = cards['id']
parsedData.append(cardData)
return render(request, 'graphs/graphs.html', {'data': parsedData})
else:
return redirect('index')
错误
KeyError at /graphs/graphs/
'name'
在我看来,我正在像这样访问数据,
{% for key in cards %}
<tr>
<td>{{ key.name }}</td>
<td>{{ key.manaCost }}</td>
<td>{{ key.colors }}</td>
<td>{{ key.type }}</td>
<td>{{ key.rarity }}</td>
<td>{{ key.set }}</td>
<td>{{ key.text }}</td>
<td>{{ key.flavor }}</td>
<td>{{ key.artist }}</td>
<td>{{ key.power }}</td>
<td>{{ key.toughness }}</td>
<td>{{ key.layout }}</td>
<td>{{ key.multiverseid }}</td>
<td>{{ key.id }}</td>
</tr>
{% endfor %}
为什么我会收到 key 错误?
最佳答案
当你这样做的时候
json.loads(req.content.decode())
你得到一个字典,一个键,cards
.
{'cards': [<list of cards>]}
将其附加到 jsonList
没有意义,因为那时你有,
[{'cards': [<list of cards>]}
当您遍历该列表时,您将获得开始时使用的单个字典。正如我们之前所说,该字典只有一个键,cards
。 ,因此当您尝试访问 name
时会出现 key 错误不存在的 key 。
你真的想遍历 [<list of cards>]
, 所以设置 jsonList
改为该列表。
req = requests.get('https://api.magicthegathering.io/v1/cards')
jsonData = json.loads(req.content.decode())
jsonList = jsonData['cards']
for cards in jsonList:
cardData = {} # move this line inside the loop
cardData['name'] = cards['name']
...
# make sure this line is inside the loop so that you append
# every card to parsedData
parsedData.append(cardData)
如评论和其他答案中所述,您可以使用请求的 json()
简化代码的方法:
req = requests.get('https://api.magicthegathering.io/v1/cards')
jsonList = req.json()['cards']
for cards in jsonList:
...
关于python - 在 Django 中使用请求解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36617646/