简体   繁体   English

使用python进行JSON读取:KeyError

[英]JSON reading with python: KeyError

For a project to create a database, I wanted to convert .json files into .sqlite3 files using python (currently running Python 3.6.4 on Windows 10). 对于创建数据库的项目,我想使用python(当前在Windows 10上运行Python 3.6.4)将.json文件转换为.sqlite3文件。 Below is the code designed to read a json file 以下是旨在读取json文件的代码

...

with open('C:/Documents/{}/Posts.json'.format(forum), encoding="utf8") as f:
            row = json.load(f)
            parent_id = row['_Id']
            body = format_data(row['_Body'])
            score = row['_Score']
            comment_id = row['_Id']
            comment_id_type = row['_PostTypeId']
            parent_id_type = row['_PostTypeId']
            accepted_answer_id = row['_AcceptedAnswerId']
            accepted_parent_id = row['_ParentId']

            ...

While running this code I encounter this error. 在运行此代码时,我遇到此错误。

File "C:\Python\data base.py", line 85, in <module>
parent_id = row['_Id']
KeyError: '_Id'

I've read into this error finding that, according to the official python docs, the exception KeyError is 根据官方的python文档,我已阅读此错误发现,发现KeyError异常

Raised when a mapping (dictionary) key is not found in the set of existing keys. 在现有键集中找不到映射(字典)键时引发。

Now I've had trouble understanding this syntax because '_Id' exists in the json file(as seen below) 现在我在理解这种语法时遇到了麻烦,因为json文件中存在“ _Id”(如下所示)

{
   "posts": {
      "row": [
         {
            "_Id": "1",
            "_PostTypeId": "1",
            "_AcceptedAnswerId": "3",
            "_CreationDate": "2016-08-02T15:39:14.947",
            "_Score": "5",
            "_ViewCount": "254",
            "_Body": "<p>What does \"backprop\" mean? I've Googled it, but it's showing backpropagation.</p>\n\n<p>Is the \"backprop\" term basically the same as \"backpropagation\" or does it have a different meaning?</p>\n",
            "_OwnerUserId": "8",
            "_LastEditorUserId": "7488",
            "_LastEditDate": "2017-05-28T13:48:02.003",
            "_LastActivityDate": "2017-05-28T13:48:02.003",
            "_Title": "What is \"backprop\"?",
            "_Tags": "<neural-networks><definitions><terminology>",
            "_AnswerCount": "3",
            "_CommentCount": "3"
         },

(This is a json from AI:stackexchange data) (这是来自AI:stackexchange数据的json)

I request someone help give me a solution to my KeyError, for other sources I have searched yield me no help 我要求有人帮我解决KeyError问题,对于我搜索过的其他资源没有帮助

Please and thank you, in advance. 请先谢谢你。

First you have to access "posts" 首先,您必须访问"posts"

with open('C:/Documents/{}/Posts.json'.format(forum), encoding="utf8") as f:
    j = json.load(f)
    for row in j['posts']['row']:
        parent_id = row['_Id']
        body = format_data(row['_Body'])
        # ...

KeyError is raised when you request for a key which does not exist in the dictionary. 当您请求字典中不存在的键时,会引发KeyError。 In your case, from the json, it seems you have to access it like so, 就您而言,从json看来,您必须像这样访问它,

json['posts' ]['row'][0].

posts is a dict. 帖子是一个命令。 row is a list of dicts. row是字典列表。 A list is ordered, that's why we can index into it. 一个列表是有序的,这就是为什么我们可以索引它。

Full code: 完整代码:

with open('C:/Documents/{}/Posts.json'.format(forum), encoding="utf8") as f:
            jsondict = json.load(f)

            # Remember, posts > row > first_index
            row = jsondict['posts']['row'][0]
            parent_id = row['_Id']
            body = format_data(row['_Body'])
            score = row['_Score']
            comment_id = row['_Id']
            comment_id_type = row['_PostTypeId']
            parent_id_type = row['_PostTypeId']
            accepted_answer_id = row['_AcceptedAnswerId']
            accepted_parent_id = row['_ParentId']
            ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM