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

如何使用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 id as a string ("id": "1"), so we convert the integer id from the DataFrame to a string using str(row['id']). If your DataFrame's id is already a string, you can skip this step.
  • Readable JSON: The indent=4 parameter in json.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 name column. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 08:32:51