You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 (with statements): 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 return after 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=4 parameter in json.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 04:53:03