Python读取JSON触发KeyError问题求助(JSON转SQLite3项目)
解决JSON读取时的KeyError问题
你这是踩了JSON嵌套结构的典型坑!咱们先把问题拆明白:
你给出的JSON结构是这样的:
{ "posts": { "row": [ { "_Id": "1", "_PostTypeId": "1", "_AcceptedAnswerId": "3", ... } ] } }
但你的代码里直接用row = json.load(f)把整个JSON文件加载成了最外层的字典——这个字典里只有posts这一个键,_Id根本不在这一层,它藏在posts下面的row数组里的每个元素中。这就是为什么会抛出KeyError: '_Id'。
修复方案
调整代码逻辑,先拿到嵌套的行数据列表,再遍历每个元素提取字段:
import json # 假设你的format_data函数已定义 def format_data(body): # 你的文本处理逻辑 return body forum = "your_forum_name" # 替换为实际的forum值 with open('C:/Documents/{}/Posts.json'.format(forum), encoding="utf8") as f: # 加载整个JSON数据 json_data = json.load(f) # 获取posts下的row列表(这才是包含所有帖子数据的数组) post_list = json_data['posts']['row'] # 遍历每个帖子条目 for post in post_list: # 现在从单个post字典里提取字段就没问题了 parent_id = post['_Id'] body = format_data(post['_Body']) score = post['_Score'] comment_id = post['_Id'] comment_id_type = post['_PostTypeId'] parent_id_type = post['_PostTypeId'] # 建议用get()处理可选字段,避免因字段缺失再次报错 accepted_answer_id = post.get('_AcceptedAnswerId') accepted_parent_id = post.get('_ParentId') # 这里添加你的SQLite插入逻辑,例如: # cursor.execute("INSERT INTO posts VALUES (?, ?, ?, ...)", (parent_id, body, score, ...))
额外小建议
用dict.get(key)代替直接dict[key]是个实用技巧——如果某些帖子没有_AcceptedAnswerId或_ParentId这类非必填字段,get()会返回None(你也可以指定默认值,比如post.get('_AcceptedAnswerId', '0')),不会直接导致程序崩溃,让代码更健壮。
内容的提问来源于stack exchange,提问作者Rich Kirk
相关产品推荐
相关产品推荐

