Python-KeyError:0

时间:2019-04-30 01:33:42

标签: python json python-3.x

每次运行此代码时,我都会不断得到KeyError: 0,我不知道它是否在json文件中找不到"title": "Screenshots",或者有什么帮助将受到欢迎。谢谢!

代码:

import json

obj  = json.load(open("path/to/json/file"))

# Iterate through the objects in the JSON and pop (remove)
# the obj once we find it.
for i in range(len(obj)):
    if obj[i]["title"] == "Screenshots":
        obj.pop(i)
        break

open("path/to/json/file", "w").write(
    json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))
)

JSON文件:

{
   "minVersion": "0.1",
   "class": "DepictionTabView",
   "tintColor": "#2cb1be",
   "headerImage": "",
   "tabs": [
      {
         "tabname": "Details",
         "class": "DepictionStackView",
         "tintColor": "#2cb1be",
         "views": [
            {
               "class": "DepictionSubheaderView",
               "useBoldText": true,
               "useBottomMargin": false,
               "title": "Description"
            },
            {
               "class": "DepictionMarkdownView",
               "markdown": "Some dummy text...",
               "useRawFormat": true
            },
            {
               "class": "DepictionSeparatorView"
            },
            {
               "class": "DepictionSubheaderView",
               "useBoldText": true,
               "useBottomMargin": false,
               "title": "Screenshots"
            },
            {
               "class": "DepictionScreenshotsView",
               "itemCornerRadius": 6,
               "itemSize": "{160, 284.44444444444}",
               "screenshots": [
                  {
                     "accessibilityText": "Screenshot",
                     "url": "http://example.com/image.png",
                  }
               ]
            },
            {
               "class": "DepictionSeparatorView"
            },
            {
               "class": "DepictionSubheaderView",
               "useBoldText": true,
               "useBottomMargin": false,
               "title": "Information"
            },
            {
               "class": "DepictionTableTextView",
               "title": "Author",
               "text": "User"
            },
            {
               "class": "DepictionSpacerView",
               "spacing": 16
            },
            {
               "class": "DepictionStackView",
               "views": [
                  {
                     "class": "DepictionTableButtonView",
                     "title": "Contact",
                     "action": "http://example.com/",
                     "openExternal": true
                  }
               ]
            },
            {
               "class": "DepictionSpacerView",
               "spacing": 16
            }
         ]
      },
      {
         "tabname": "History",
         "class": "DepictionStackView",
         "views": [
            {
               "class": "DepictionSubheaderView",
               "useBoldText": true,
               "useBottomMargin": false,
               "title": ""
            },
            {
               "class": "DepictionMarkdownView",
               "markdown": "<ul>\n<li>Initial release.<\/li>\n<\/ul>",
               "useRawFormat": true
            }
         ]
      }
   ]
}

2 个答案:

答案 0 :(得分:3)

obj是一种读dict的阅读方式。您正在尝试将其作为具有整数索引的列表进行访问。这段代码:

for i in range(len(obj)):
    if obj[i]["title"] == "Screenshots":
        ...

首先呼叫obj[0]["title"],然后呼叫obj[1]["title"],依此类推。由于obj不是列表,因此这里的0被解释为键-并且由于obj没有键0,您将得到一个{{1} }。

一种更好的方法是通过键和值遍历字典:

KeyError

答案 1 :(得分:0)

在循环中,range产生整数,第一个为0。 json中没有整数作为键,因此会立即引发KeyError

相反,循环遍历obj.items()会产生键值对。由于您的某些条目本身不是dict,因此访问obj[i]['title']时需要格外小心。

for k, v in obj.items():
    if isinstance(v, dict) and v.get("title") == "Screenshots":
        obj.pop(k)
        break