How to Convert CSV to JSON in Python FOSS
Problem
Convert a CSV file to JSON using Aspose.Cells FOSS in Python. Load the CSV with load_csv_workbook(), read each row using iter_rows() to build a Python list of dictionaries, then serialize to JSON using the standard json module.
Prerequisites
To convert CSV to JSON using Aspose.Cells FOSS in Python, ensure your environment meets the following requirements.
- Python 3.7 or later installed
- Install Aspose.Cells FOSS via
pip install aspose-cells-foss>=26.3.1 - Import the library using
from aspose.cells_foss import load_csv_workbook - Basic familiarity with Python file handling and the standard
jsonmodule
Conversion Steps
Step 1: Load the CSV File
Use the load_csv_workbook() convenience function to load the CSV file into a new workbook. This initializes the in-memory representation of the spreadsheet data.
from aspose.cells_foss import load_csv_workbook
workbook = load_csv_workbook("data.csv")
worksheet = workbook.worksheets[0]Step 2: Read Headers and Rows
Use iter_rows(values_only=True) to extract all rows as tuples of cell values. The first row is treated as the header row.
all_rows = list(worksheet.cells.iter_rows(values_only=True))
# Read the header row (first row)
headers = [str(v) if v is not None else f"col{i}" for i, v in enumerate(all_rows[0])]Step 3: Build a List of Dicts and Serialize to JSON
Iterate the remaining rows, build a dict per row keyed by the header names, then use json.dump() to write the JSON file.
import json
rows = [dict(zip(headers, row)) for row in all_rows[1:]]
with open("output.json", "w", encoding="utf-8") as f:
json.dump(rows, f, indent=2, default=str)
print(f"Converted {len(rows)} rows to output.json")Code Example
The complete end-to-end example combining all three steps:
import json
from aspose.cells_foss import load_csv_workbook
# Step 1: Load CSV
workbook = load_csv_workbook("data.csv")
worksheet = workbook.worksheets[0]
# Step 2: Extract all rows; first row is headers
all_rows = list(worksheet.cells.iter_rows(values_only=True))
if not all_rows:
print("No data found in CSV")
else:
headers = [str(v) if v is not None else f"col{i}" for i, v in enumerate(all_rows[0])]
# Step 3: Build list of dicts from remaining rows
rows = [dict(zip(headers, row)) for row in all_rows[1:]]
# Step 4: Write JSON
with open("output.json", "w", encoding="utf-8") as f:
json.dump(rows, f, indent=2, default=str)
print(f"Converted {len(rows)} rows to output.json")Supported Formats
Aspose.Cells FOSS supports loading CSV files and exporting to JSON via the approach shown above. The library also supports direct save to other formats.
| Format | Extension | Notes |
|---|---|---|
| CSV (input) | .csv | Load with load_csv_workbook("file.csv") |
| JSON (output) | .json | Built with Python json.dump() after iterating cells |
| XLSX (input/output) | .xlsx | Standard Excel Open XML format |
| Markdown (output) | .md | Use wb.save_as_markdown("file.md") |