如何将指定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.DictReaderlets us reference columns by their header names (likerow["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()withfloat(). - Readable JSON Output: The
indent=4parameter injson.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
相关产品推荐
相关产品推荐

