Python读写JSON文件时datetime追加引发KeyError问题求助
问题:追加日期后遍历JSON出现KeyError: 'available'
我测试以下代码,模拟从API获取数据后追加last_updated_date并写入JSON文件:
from datetime import datetime from pathlib import Path import json from_api_response_data = [ { "active": True, "available": True, "test1": True, "test2": "Testing Only", "test3": False, "test_name": "Tester 1", "id": "12345abcxyz", "test_url": { "url": "/something/others/api/v1/abc123" } }, { "active": True, "available": True, "test1": False, "test2": "This also a test", "test3": False, "test_name": "Tester 2", "id": "12345abcxyz678", "test_url": { "url": "/something/others/api/v1/abc1234" } } ] filename = 'testingfile.json' today = datetime.datetime.now().isoformat() from_api_response_data.append( { 'last_updated_date': today } ) Path(filename).write_text( json.dumps(from_api_response_data, default=vars, indent=2) ) test_file_json_read = json.loads( Path(filename).read_text() ) for test in test_file_json_read: if test['available']: print("true available")
移除追加日期的代码时,遍历读取test['available']正常,控制台输出两行"true available";但追加日期后,执行if test['available']时出现KeyError: 'available'。生成的testingfile.json内容如下:
[ { "active": true, "available": true, "test1": true, "test2": "Testing Only", "test3": false, "test_name": "Tester 1", "id": "12345abcxyz", "test_url": { "url": "/something/others/api/v1/abc123" } }, { "active": true, "available": true, "test1": false, "test2": "This also a test", "test3": false, "test_name": "Tester 2", "id": "12345abcxyz678", "test_url": { "url": "/something/others/api/v1/abc1234" } }, { "last_updated_date": "2022-11-25T09:48:12.765296" } ]
原因分析
你用append()把仅含last_updated_date的对象作为第三个元素加到了数组末尾,而不是给数组里的每个测试对象添加该字段。遍历整个数组时,第三个元素没有available键,直接用test['available']访问不存在的键就会触发KeyError。
解决方案
根据需求可选择以下两种处理方式:
1. 给每个测试对象添加更新日期
如果需要给每一条测试数据标记更新时间,遍历原数组的每个对象直接添加字段:
today = datetime.datetime.now().isoformat() # 遍历每个测试条目,添加last_updated_date字段 for item in from_api_response_data: item['last_updated_date'] = today
生成的JSON中每个测试对象都会包含last_updated_date,遍历不会出现键缺失问题。
2. 单独保存更新日期,不影响遍历
如果要把更新日期作为独立信息存储,建议修改数据结构,将原数组包裹在一个对象中:
today = datetime.datetime.now().isoformat() # 重构数据结构,将测试数组和更新日期放在同一个对象中 output_data = { 'tests': from_api_response_data, 'last_updated_date': today } # 写入文件 Path(filename).write_text(json.dumps(output_data, indent=2)) # 读取时遍历tests字段 test_file_json_read = json.loads(Path(filename).read_text()) for test in test_file_json_read['tests']: if test['available']: print("true available")
或者,若不想修改结构,遍历前先检查键是否存在:
for test in test_file_json_read: # 用get()方法,键不存在时返回None,不会触发KeyError if test.get('available'): print("true available")
内容的提问来源于stack exchange,提问作者user1897151
相关产品推荐
相关产品推荐

