Python解析JSON文件遇KeyError: 'data_block',求格式转换方案
Hey there! Let's sort out that KeyError: 'data_block' you're running into and get your code working as expected.
What's Causing the Error?
Looking at your JSON structure, the data_block isn't directly under the root data object—it's nested one level deeper inside the response key. When you try to access data["data_block"] directly, Python can't find that key at the top level, which triggers the KeyError.
Here's your JSON structure broken down for clarity:
{ "response": { "numFound": 1, "data_block": [ { "Number": "11097", "ID": -61000, "Version": "18", "Sequence": ["1", "2", "3"], "Status": ["Booked", "Canceled", "Canceled"], "Name": "abc", "EmailAddress": "abc@test.com" } ] } }
Corrected Code
Here's the fixed code that properly navigates the nested JSON structure, formats the Sequence and Status lists with | separators, and outputs the exact format you need:
import json # Load JSON data safely with a context manager (ensures file is closed properly) with open('data.json', 'r') as f: data = json.load(f) # Access data_block by first going into the "response" key data_entries = data["response"]["data_block"] # Process each entry in data_block (works even if there are multiple entries later) for entry in data_entries: number = entry["Number"] sequence_str = "|".join(entry["Sequence"]) status_str = "|".join(entry["Status"]) # Format the output as Number~Sequence~Status result = f"{number}~{sequence_str}~{status_str}" print(result)
Expected Output
When you run this code, you'll get exactly the output format you requested:
11097~1|2|3~Booked|Canceled|Canceled
Quick Best Practice Note
Using the with statement to open your JSON file is better than directly calling open()—it automatically closes the file after reading, even if an error pops up during processing.
内容的提问来源于stack exchange,提问作者rkj

