Python读取JSON触发KeyError,如何修复获取totalQuantity的问题
问题:读取JSON时触发KeyError: 'totalQuantity'错误的修复方案
问题详情
原代码
with open('C:/asg/response2.json') as json_file: data2 = json.load(json_file) if 'priceResponse' in data2: item = data2['priceResponse']['PriceAvailabilityList'][0] property_valuesa.append(item['totalQuantity']) property_values2a.append(item['PriceAvailabilityList']['price']) print (property_valuesa) input ("key enter")
报错信息
property_valuesa.append(item['totalQuantity']) KeyError: 'totalQuantity'
读取的JSON示例
{ "priceResponse": { "customerNo": "2312312", "userName": "23131@er.com", "PriceAvailabilityList": [ { "sku": "12133223", "mfgPN": "DELL-sdad", "status": "Not authorized to buy", "GlobalProductStatusCode": "Not authorized to buy", "lineNumber": "1" }, { "sku": "38384774", "mfgPN": "DELL-E322323H", "mfgCode": "23232", "status": "Active", "description": "27 MON 323232", "GlobalProductStatusCode": "Active", "price": "195.72", "totalQuantity": "138", "AvailabilityByWarehouse": [ { "warehouseInfo": { "number": "123", "zipcode": "23344", "city": "test, TT", "addr": "testaddress" }, "qty": "0" }, { "warehouseInfo": { "number": "123", "zipcode": "2344", "city": "TEST, TT", "addr": "testaddress Drive" }, "qty": "0" }, { "warehouseInfo": { "number": "233", "zipcode": "213", "city": "TEST, te", "addr": "testaddress Pkwy" }, "qty": "138" }, { "warehouseInfo": { "number": "243", "zipcode": "34324", "city": "test, tets", "addr": "test Way" }, "qty": "0" }, { "warehouseInfo": { "number": "2312", "zipcode": "2312", "city": "test, TS", "addr": "test" }, "qty": "0" } ], "lineNumber": "1" } ] } }
错误原因
- 索引取值错误:你直接取了
PriceAvailabilityList数组的第0个元素,但该元素没有totalQuantity字段,这个字段实际在数组的第1个元素(索引为1)中。 - 字段路径错误:
item['PriceAvailabilityList']['price']逻辑错误,item本身就是PriceAvailabilityList的子元素,不存在嵌套的PriceAvailabilityList字段,price是item的直接属性。 - 缺少字段存在判断:未检查目标字段是否存在,一旦元素缺少对应字段就会触发KeyError。
修复后的代码
方案1:取指定索引的目标元素
如果只需要获取第1个元素的totalQuantity和price,可以这样修改:
# 先初始化存储列表 property_valuesa = [] property_values2a = [] with open('C:/asg/response2.json') as json_file: data2 = json.load(json_file) if 'priceResponse' in data2: # 取数组的第1个元素(索引为1) item = data2['priceResponse']['PriceAvailabilityList'][1] # 先判断字段存在再取值,避免报错 if 'totalQuantity' in item: property_valuesa.append(item['totalQuantity']) if 'price' in item: property_values2a.append(item['price']) print(property_valuesa) print(property_values2a) input("按回车退出")
方案2:遍历所有元素收集有效数据
如果需要收集数组中所有包含totalQuantity和price的元素数据,推荐用遍历方式:
property_valuesa = [] property_values2a = [] with open('C:/asg/response2.json') as json_file: data2 = json.load(json_file) if 'priceResponse' in data2 and 'PriceAvailabilityList' in data2['priceResponse']: # 遍历数组中所有元素 for item in data2['priceResponse']['PriceAvailabilityList']: # 只处理同时存在两个目标字段的元素 if 'totalQuantity' in item and 'price' in item: property_valuesa.append(item['totalQuantity']) property_values2a.append(item['price']) print(property_valuesa) print(property_values2a) input("按回车退出")
补充说明
- 处理JSON数据时,永远不要默认字段一定存在,务必加存在性判断,避免KeyError。
- 也可以用
get方法简化判断,比如item.get('totalQuantity'),字段不存在时会返回None而非报错。
内容的提问来源于stack exchange,提问作者alex1290
相关产品推荐
相关产品推荐

