Python实现嵌套JSON转CSV:新手遭遇输出格式不符问题求助
Hey there! Let's get your JSON-to-CSV conversion working exactly how you want it. The problem with your current code is that it's flattening all nested arrays into separate columns (like item_item_batters_batter_0_id), but we need to generate every possible combination of batter and topping paired with the base donut details—resulting in that m*n row count you mentioned.
Here's the Solution Code
This script will iterate through each donut, then create a row for every batter-topping combination:
import json import csv def json_to_csv(json_data, csv_path): # Define the CSV headers to match your desired output headers = ["id", "type", "name", "batter", "topping"] rows = [] # Loop through each top-level entry in your JSON array for entry in json_data: item = entry["item"] # Extract the core donut information that stays consistent across rows base_details = { "id": item["id"], "type": item["type"], "name": item["name"] } # Get the full list of batters and toppings for this donut all_batters = item["batters"]["batter"] all_toppings = item["topping"] # Generate every combination of batter and topping for batter in all_batters: batter_type = batter["type"] for topping in all_toppings: topping_type = topping["type"] # Combine base details with the current batter/topping pair row = { **base_details, "batter": batter_type, "topping": topping_type } rows.append(row) # Write the collected rows to CSV with open(csv_path, "w", newline="", encoding="utf-8") as csv_file: writer = csv.DictWriter(csv_file, fieldnames=headers, quoting=csv.QUOTE_ALL) writer.writeheader() writer.writerows(rows) print(f"Done! Wrote {len(rows)} rows to {csv_path}") if __name__ == "__main__": import sys # Simplified command line arguments (no need for the "node" parameter anymore) if len(sys.argv) != 3: print("\nUsage: python json_to_csv.py <json_in_file_path> <csv_out_file_path>\n") sys.exit(1) json_file = sys.argv[1] csv_output = sys.argv[2] # Load the JSON data from file with open(json_file, "r", encoding="utf-8") as f: raw_json = json.load(f) # Run the conversion json_to_csv(raw_json, csv_output)
Key Changes & Explanations
- No more recursive flattening: Instead of turning arrays into columns, we use nested loops to create a row for every batter-topping pair (this is called a Cartesian product).
- Clean base details: We extract the fixed donut info (id, type, name) once per item, then reuse it for every combination.
- Simplified arguments: The original
nodeparameter isn't needed here—we directly access theitemkey in each JSON entry.
How to Run It
Use this command (adjust paths to match your files):
C:\Users\user1>python C:/Users/user1/PycharmProjects/pro1/venv/file3.py D:/jsonfile1.json D:/filecsv2.csv
What the Output Looks Like
Your CSV will have exactly the format you want:
"id","type","name","batter","topping" "0001","donut","Cake","Regular","None" "0001","donut","Cake","Regular","Glazed" "0001","donut","Cake","Regular","Sugar" ... "0001","donut","Cake","Devil's Food","Maple"
This works even if you add more donut entries to your JSON—each will generate its own set of batter-topping rows automatically.
内容的提问来源于stack exchange,提问作者Bhaskar Das

