import os
import json
import csv

def merge_json_to_csv(folder_path, output_csv_path):
    # This list will store all the JSON data
    all_data = []

    # Iterate through all files in the folder
    for file in os.listdir(folder_path):
        if file.endswith('.json'):
            file_path = os.path.join(folder_path, file)

            # Read and parse the JSON file
            with open(file_path, 'r') as json_file:
                data = json.load(json_file)
                all_data.extend(data) # Add the data from this file to the main list

    # Write data to CSV
    with open(output_csv_path, 'w', newline='', encoding='utf-8') as csv_file:
        writer = csv.writer(csv_file)
        writer.writerow(["name", "prompt", "negative_prompt"])
        for item in all_data:
            # Retrieve each value, or use an empty string if the key is missing
            name = item.get('name', '')
            prompt = item.get('prompt', '')
            negative_prompt = item.get('negative_prompt', '')

            writer.writerow([name, prompt, negative_prompt])

# Example usage
folder_path = r'G:\Fooocus_win64_2-1-791\Fooocus\sdxl_styles' # Replace with your folder path
output_csv_path = r'G:\automatic1111\stable-diffusion-webui\styles.csv' # Path for the output CSV file
merge_json_to_csv(folder_path, output_csv_path)
