Python实现从JSON字典列表中批量生成独立JSON文件的方法及键缺失问题解决
Solution: Extract JSON Elements to Individual Files with Preserved 'native_data' Key
I see the issue you're facing—right now you're grabbing just the value of the native_data field, but you need to keep it wrapped under its original key in the output files. Here's a clean, efficient way to fix this, plus some best practice improvements to your code:
Corrected Code
import json import logging def ExtractJsonPrice(file_path): # Use context manager to safely open/close the input file with open(file_path, "r") as jsonFile: try: json_data = json.load(jsonFile) except ValueError as e: print("Error loading JSON file:", e) logging.error("Exception occurred while loading JSON", exc_info=True) return # Exit function if loading fails for item in json_data: # Get the filename from the 'id' field (add .json extension) file_name = f"{item['id']}.json" # Create the content dict with the 'native_data' key preserved json_content = {"native_data": item["native_data"]} # Use context manager to write each output file with open(file_name, "w") as output_file: json.dump(json_content, output_file, indent=4) # Indent for readable formatting
Key Fixes & Improvements:
- Preserve the 'native_data' key: Instead of assigning
json_content = item['native_data'], we wrap the value in a new dictionary with the original key:{"native_data": item["native_data"]}. This directly gives you the structure you need for each output file. - Context managers (
withstatements): These automatically close files after use, preventing resource leaks and making the code more robust than manually opening/closing files. - Better error handling: Added a
returnafter logging the error to avoid trying to process invalid JSON data. Also included the specific error message in the print statement for clearer debugging. - Readable output: The
indent=4parameter injson.dump()formats the output JSON with proper spacing, making it easier to read and verify.
Example Output:
For the first item in your input JSON, the file 3dsdsa_a_12sss.json will contain:
{ "native_data": { "PopOrGuess": null, "role": "D", "TSX": "Included" } }
内容的提问来源于stack exchange,提问作者AviC
相关产品推荐
相关产品推荐

