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

如何将指定CSV文件转换为目标JSON格式?代码实现咨询

CSV to JSON Conversion for SpikeData Structure

Got it, let's wrap up this Python script to convert your specific CSV into the required SpikeData JSON structure. Here's the complete, working implementation with clear explanations:

Full Working Code

import csv
import json

def read_csv(csv_file_path):
    # Initialize the exact SpikeData structure we need
    spike_data = {
        "SpikeData": {
            "RPM": [],
            "Load Current": [],
            "Output": []
        }
    }
    
    with open(csv_file_path, mode='r', newline='') as csv_file:
        # Use DictReader to access rows by header name
        csv_reader = csv.DictReader(csv_file)
        
        for row in csv_reader:
            # Convert string values to integers (matches your sample data types)
            spike_data["SpikeData"]["RPM"].append(int(row["RPM"]))
            spike_data["SpikeData"]["Load Current"].append(int(row["Load Current"]))
            spike_data["SpikeData"]["Output"].append(int(row["Output"]))
    
    return spike_data

def write_json(data, json_file_path):
    with open(json_file_path, mode='w') as json_file:
        # Write with indentation for human-readable output
        json.dump(data, json_file, indent=4)

# Run the conversion when the script is executed directly
if __name__ == "__main__":
    # Replace these paths with your actual file locations
    input_csv = "your_data.csv"
    output_json = "spike_data_output.json"
    
    converted_data = read_csv(input_csv)
    write_json(converted_data, output_json)
    print(f"Conversion complete! Check {output_json} for results.")

Key Details Breakdown

  • Structured Initialization: We start by defining the exact JSON structure you specified, so we don't have to dynamically build keys later.
  • DictReader for Clarity: Using csv.DictReader lets us reference columns by their header names (like row["Load Current"]), which makes the code intuitive and easy to maintain.
  • Data Type Fix: CSV files store all values as strings, so we convert each entry to an integer to match the numeric nature of your data. If you ever need floating-point values, just swap int() with float().
  • Readable JSON Output: The indent=4 parameter in json.dump() ensures the resulting JSON is formatted neatly, not just a single line of text.

Sample Output JSON

When you run this with your provided CSV data, the output file will look like this:

{
    "SpikeData": {
        "RPM": [
            1200,
            1500
        ],
        "Load Current": [
            3,
            4
        ],
        "Output": [
            12,
            13
        ]
    }
}

Just update the file paths in the __main__ block to match your setup, and you're ready to go!

内容的提问来源于stack exchange,提问作者Code Name X

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:03:05