如何用Python读取文件夹中所有JSON文件并合并为单个JSON文件?
Absolutely! Merging all the JSON files in your C:/Users/Desktop/soccer_data2/ folder into a single JSON file is totally achievable. Below are the most practical methods depending on your setup and the structure of your JSON files.
Method 1: Using Python (Cross-Platform, Flexible)
Python is the go-to choice here because it works on all operating systems and handles different JSON structures easily. Here's how to do it:
Case 1: Each JSON file is a standalone object (e.g., player stats, match data)
If every file contains a single JSON object and you want to combine them into an array (list) in the final file:
import os import json # Define your target folder path (raw string avoids escape character issues) folder_path = r"C:/Users/Desktop/soccer_data2/" merged_data = [] # Loop through all files in the folder for filename in os.listdir(folder_path): # Only process JSON files if filename.lower().endswith(".json"): file_full_path = os.path.join(folder_path, filename) # Load and parse the JSON file with open(file_full_path, 'r', encoding='utf-8') as json_file: try: data = json.load(json_file) merged_data.append(data) except json.JSONDecodeError: print(f"Skipping invalid JSON file: {filename}") # Write the merged data to a new JSON file output_file = os.path.join(folder_path, "merged_soccer_data.json") with open(output_file, 'w', encoding='utf-8') as outfile: json.dump(merged_data, outfile, indent=4) print(f"Merged data saved to {output_file}")
Case 2: Each JSON file is a dictionary (key-value pairs)
If you want to merge all key-value pairs into one large dictionary (note: duplicate keys will be overwritten by later files):
import os import json folder_path = r"C:/Users/Desktop/soccer_data2/" merged_dict = {} for filename in os.listdir(folder_path): if filename.lower().endswith(".json"): file_full_path = os.path.join(folder_path, filename) with open(file_full_path, 'r', encoding='utf-8') as json_file: try: data = json.load(json_file) # Merge the current file's dictionary into the main one merged_dict.update(data) except json.JSONDecodeError: print(f"Skipping invalid JSON file: {filename}") output_file = os.path.join(folder_path, "merged_soccer_dict.json") with open(output_file, 'w', encoding='utf-8') as outfile: json.dump(merged_dict, outfile, indent=4) print(f"Merged dictionary saved to {output_file}")
Key Notes for Python Method:
- Make sure Python is installed on your system (you can check by running
python --versionin your terminal/command prompt). - The
encoding='utf-8'parameter ensures special characters are handled correctly. - The error handling skips any corrupted JSON files instead of crashing the script.
Method 2: Using PowerShell (Windows Only, No Python Required)
If you're on Windows and prefer not to use Python, you can use PowerShell to do the merge:
# Set your folder path $folderPath = "C:\Users\Desktop\soccer_data2\" $mergedData = @() # Loop through all JSON files and collect data Get-ChildItem -Path $folderPath -Filter "*.json" | ForEach-Object { $fileContent = Get-Content -Path $_.FullName -Raw try { $jsonData = $fileContent | ConvertFrom-Json $mergedData += $jsonData } catch { Write-Warning "Skipping invalid JSON file: $($_.Name)" } } # Save merged data to a new file $outputPath = Join-Path -Path $folderPath -ChildPath "merged_soccer_data.json" $mergedData | ConvertTo-Json -Depth 10 | Out-File -Path $outputPath -Encoding UTF8 Write-Host "Merge complete! File saved to: $outputPath"
How to Run This:
- Open PowerShell (search for "PowerShell" in the Windows Start Menu).
- Copy and paste the script, adjusting the
$folderPathif needed. - Press Enter to execute.
内容的提问来源于stack exchange,提问作者xhaka




