如何使用Python从员工信息DataFrame批量生成指定格式的JSON文件
Solution to Generate Employee JSON Files
Here's a straightforward way to generate the 10 JSON files from your DataFrame, following the exact format you specified:
Step 1: Import Required Libraries
First, make sure you have pandas installed (if not, run pip install pandas). Then import the necessary modules:
import pandas as pd import json
Step 2: Iterate Through the DataFrame and Generate JSON Files
Assuming your DataFrame is named employee_df, use iterrows() to loop through each row. For each row, construct the required JSON structure and write it to a file named after the employee's name:
# Example DataFrame (replace this with your actual DataFrame) employee_df = pd.DataFrame({ 'id': [1, 2, 3], 'name': ['Employee1', 'Employee2', 'Employee3'], 'team': ['Team1', 'Team2', 'Team1'] }) # Loop through each row in the DataFrame for index, row in employee_df.iterrows(): # Build the JSON structure with fixed "Company" field employee_json = { "Company": "Company", "id": str(row['id']), # Convert id to string as shown in your example "name": row['name'], "team": row['team'] } # Define the filename using the employee's name filename = f"{row['name']}.json" # Write the JSON object to the file with open(filename, 'w') as json_file: json.dump(employee_json, json_file, indent=4) # indent=4 makes the JSON readable
Key Notes:
- String Conversion for ID: The example shows
idas a string ("id": "1"), so we convert the integeridfrom the DataFrame to a string usingstr(row['id']). If your DataFrame'sidis already a string, you can skip this step. - Readable JSON: The
indent=4parameter injson.dump()formats the JSON with proper indentation for readability. If you prefer minified JSON, remove this parameter. - File Naming: The filename is directly taken from the
namecolumn. If any employee names contain special characters (like spaces, slashes, etc.), you might want to sanitize the filename first to avoid errors (e.g., replace spaces with underscores).
This code will generate a separate JSON file for each employee, named like Employee1.json, Employee2.json, etc., each containing the exact structure you need.
内容的提问来源于stack exchange,提问作者Harper
相关产品推荐
相关产品推荐

