Python 使用Django中的请求解析JSON

Python 使用Django中的请求解析JSON,python,json,django,Python,Json,Django,我正在django应用程序中对请求进行api调用。我的名字一直有个关键错误。json响应非常大,所以我只挑选某些字段来使用。但是错误出现在json列表的第一项上 json的前几行如下所示 "cards": [ { "name": "Air Elemental", "manaCost": "{3}{U}{U}", "cmc": 5, "colors": [ "Blue" ], "type": "Crea

我正在django应用程序中对请求进行api调用。我的名字一直有个关键错误。json响应非常大,所以我只挑选某些字段来使用。但是错误出现在json列表的第一项上

json的前几行如下所示

"cards": [
    {
      "name": "Air Elemental",
      "manaCost": "{3}{U}{U}",
      "cmc": 5,
      "colors": [
        "Blue"
      ],
      "type": "Creature — Elemental",
      "types": [
        "Creature"
      ],
      "subtypes": [
        "Elemental"
      ],
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')
 {% 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 %}
在我看来,我是这样解析json的

"cards": [
    {
      "name": "Air Elemental",
      "manaCost": "{3}{U}{U}",
      "cmc": 5,
      "colors": [
        "Blue"
      ],
      "type": "Creature — Elemental",
      "types": [
        "Creature"
      ],
      "subtypes": [
        "Elemental"
      ],
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')
 {% 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 %}
错误

KeyError at /graphs/graphs/
'name'
在我看来,我是这样访问数据的

"cards": [
    {
      "name": "Air Elemental",
      "manaCost": "{3}{U}{U}",
      "cmc": 5,
      "colors": [
        "Blue"
      ],
      "type": "Creature — Elemental",
      "types": [
        "Creature"
      ],
      "subtypes": [
        "Elemental"
      ],
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')
 {% 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.name}
{{key.manaCost}
{{key.colors}}
{{key.type}
{{key.rarity}}
{{key.set}}
{{key.text}}
{{key.flavor}
{{key.artist}}
{{key.power}
{{key.韧性}}
{{key.layout}}
{{key.multiverseid}
{{key.id}
{%endfor%}

为什么我收到钥匙错误?

因为在
卡片中找不到钥匙
名称

要调试此功能,您可能需要打印每个dict卡,并查看dict是不规则的


祝你好运

因为在
卡片
目录中找不到键
名称

要调试此功能,您可能需要打印每个dict卡,并查看dict是不规则的

祝你好运

等等,你的json是

"cards": [
    {"name": "Air Elemental",...}
]
然后你像这样加载它

jsonList = []
jsonList.append(json.loads(req.content.decode()))
这不就是jsonList吗

[
    {"cards": [{"name": "Air Elemental",...}]}
]
当你迭代它时,你会得到
{“cards”:[{“name”:“Air Elemental”,…}]}
,显然它没有key
name
。您需要迭代
jsonList['cards']

等等,您的json是

"cards": [
    {"name": "Air Elemental",...}
]
然后你像这样加载它

jsonList = []
jsonList.append(json.loads(req.content.decode()))
这不就是jsonList吗

[
    {"cards": [{"name": "Air Elemental",...}]}
]

当你迭代它时,你会得到
{“cards”:[{“name”:“Air Elemental”,…}]}
,显然它没有key
name
。如果您阅读请求文档,
jsonList=req.json()
将为您从外部API资源接收的json分配一个字典/目录列表(可能比调用
json.loads(…)
可读)


我怀疑您收到的KeyError被抛出到您的行
cardData['name']=cards['name']
,因为JSON解码过程没有像您预期的那样工作


如果失败,您是否检查了您正在迭代正确的模板变量(
用于输入数据),因为这似乎是您正在传递给模板的变量。

如果您阅读了请求文档,
jsonList=req.json()
将分配与从外部API资源接收的JSON对应的dict字典/列表(可能比调用
JSON.loads(…)


我怀疑您收到的KeyError被抛出到您的行
cardData['name']=cards['name']
,因为JSON解码过程没有像您预期的那样工作

如果失败,您是否检查了您正在迭代正确的模板变量(
用于输入数据),因为这似乎是您正在传递给模板的内容。

当您这样做时

json.loads(req.content.decode())
你会得到一本只有一个键的字典,
cards

{'cards': [<list of cards>]}
当你循环浏览该列表时,你会得到一个你开始使用的字典。正如我们前面所说,该字典有一个键,
cards
,因此当你试图访问不存在的
name
键时,会出现键错误

您确实想循环查看
[]
,因此将
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:
        ...
当你这样做的时候

json.loads(req.content.decode())
你会得到一本只有一个键的字典,
cards

{'cards': [<list of cards>]}
当你循环浏览该列表时,你会得到一个你开始使用的字典。正如我们前面所说,该字典有一个键,
cards
,因此当你试图访问不存在的
name
键时,会出现键错误

您确实想循环查看
[]
,因此将
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:
        ...

cardData['name']=cards['name']打印卡片,查看名称是否确实在其中。cardData['name']=cards['name']打印卡片,看看名字是否真的在里面。谢谢你的帮助。我在其他3个应用程序中都这么做了,效果很好。解码是因为它得到了一个JSON对象,必须是str,而不是没有解码的“bytes”。你能给我举一个你的建议和列表的例子吗?我想我是因为格式问题json的功能与我在其中使用的其他3个应用程序不同。我从你的帖子中看到的是@laike9m。这不是关于解码方法,而是关于你的json对象。为什么不打印
卡片
对象,看看它到底是什么?@wunoWhen我打印(req.content)所有的json转储。看到你所有的答案后,我非常困惑。就像我说的,我写的最后三个应用程序也是这样做的。你能更具体地说明我的代码有什么问题,或者告诉我更好的方法吗?我将非常感谢你。谢谢你的帮助。我已经在其他三个应用程序中这样做了,并且每个应用程序都有效很好。解码是因为它得到一个JSON对象必须是str,而不是没有解码的“bytes”。请给我举一个你的建议和列表的例子好吗