解析指定JSON文件按ID排序返回最大ID条目,解决KeyError问题
Fixing KeyError: 'job' & Getting the Max ID Entry from Your JSON Data
Hey there! Let's break down the problem and solve it properly.
Why the KeyError Happens
The error KeyError: 'job' pops up because not every entry in the executions list has a job key. Your current code assumes every issue has this key, but some entries are missing it—so when you try to access issue['job']['name'], Python throws an error.
Step 1: Fix the KeyError First
To avoid crashing, you can either:
- Check if
'job'exists in the issue before accessing it, or - Use the
.get()method (safer, since it returns a default value if the key doesn't exist)
Here's how to adjust your existing print loop to handle missing job entries:
import json datapath = '1.json' data = json.load(open(datapath)) for issue in data['executions']: if 'id' in issue: # Use .get() to handle missing 'job' or 'name' keys gracefully job_name = issue.get('job', {}).get('name', 'No Job Name') start_date = issue['date-started']['date'] end_date = issue['date-ended']['date'] status = issue['status'] issue_id = issue['id'] print(start_date, end_date, status, job_name, issue_id)
Step 2: Get the Entry with the Largest ID (Your Core Requirement)
Now, to sort all valid entries by ID and grab the one with the highest ID, we can:
- Filter out entries that don't have an
id(since you checked for this earlier) - Sort the filtered list by the
idvalue (convert to integer to ensure numeric sorting, not lexicographical) - Pick the last item in the sorted list (or use the
max()function directly for better efficiency)
Here's the optimized code for this:
import json datapath = '1.json' data = json.load(open(datapath)) # Filter entries that have a valid 'id' valid_entries = [issue for issue in data['executions'] if 'id' in issue] if not valid_entries: print("No valid entries with 'id' found.") else: # Use max() to directly get the entry with the largest ID (faster than sorting all) max_id_entry = max(valid_entries, key=lambda x: int(x['id'])) # Print details of the max ID entry print("Entry with the largest ID:") print(f"ID: {max_id_entry['id']}") print(f"Start Date: {max_id_entry['date-started']['date']}") print(f"End Date: {max_id_entry['date-ended']['date']}") print(f"Status: {max_id_entry['status']}") print(f"Job Name: {max_id_entry.get('job', {}).get('name', 'No Job Name')}")
Alternative: Sort If You Need the Full Ordered List
If you want the entire list sorted by ID (not just the max entry), use this instead:
sorted_entries = sorted(valid_entries, key=lambda x: int(x['id'])) max_id_entry = sorted_entries[-1] # Last item is the largest ID
Key Takeaways
- Always handle optional JSON keys with
.get()or existence checks to avoid unexpected KeyErrors. - When sorting by IDs, convert them to integers—JSON often stores IDs as strings, which would lead to wrong lexicographical sorting (e.g., "126" > "99" numerically, but not as strings).
内容的提问来源于stack exchange,提问作者Milister
相关产品推荐
相关产品推荐

