A simple and efficient Python utility to convert CSV files into JSON format with support for array and object output modes.
- Convert CSV files to JSON format
- Two output modes: array of objects or single object with keys
- Automatic data type detection
- Clean and readable JSON output
- Error handling for invalid files
No external dependencies required. Uses only Python standard library.
python3 csv_to_json.py# Convert CSV to JSON (array mode - default)
python3 csv_to_json.py input.csv -o output.json
# Convert with object mode (keyed by first column)
python3 csv_to_json.py input.csv -o output.json --mode object
# Pretty print to console
python3 csv_to_json.py input.csv
# Specify custom delimiter
python3 csv_to_json.py input.csv -o output.json --delimiter ';'from csv_to_json import CSVtoJSON
converter = CSVtoJSON('data.csv')
json_data = converter.convert(mode='array')
print(json_data)
# Save to file
converter.save('output.json', mode='array')Input CSV (data.csv):
name,age,city,salary
Alice,28,New York,75000
Bob,35,Los Angeles,85000
Charlie,42,Chicago,95000
Output JSON (array mode):
[
{
"name": "Alice",
"age": 28,
"city": "New York",
"salary": 75000
},
{
"name": "Bob",
"age": 35,
"city": "Los Angeles",
"salary": 85000
},
{
"name": "Charlie",
"age": 42,
"city": "Chicago",
"salary": 95000
}
]Output JSON (object mode with 'name' as key):
{
"Alice": {
"age": 28,
"city": "New York",
"salary": 75000
},
"Bob": {
"age": 35,
"city": "Los Angeles",
"salary": 85000
},
"Charlie": {
"age": 42,
"city": "Chicago",
"salary": 95000
}
}MIT