The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

Convert CSV to JSON with Python

Converting CSV to JSON with Python is a common task for data manipulation and integration. Here’s a straightforward way to do it using the built-in csv and json modules.

python
import csv import json def csv_to_json(csv_file_path, json_file_path): data = [] with open(csv_file_path, mode='r', encoding='utf-8') as csv_file: csv_reader = csv.DictReader(csv_file) for row in csv_reader: data.append(row) with open(json_file_path, mode='w', encoding='utf-8') as json_file: json.dump(data, json_file, indent=4) # Example usage: csv_to_json('input.csv', 'output.json')

Explanation:

  • csv.DictReader reads the CSV file and converts each row into a dictionary using the CSV headers as keys.

  • Each dictionary is appended to the data list.

  • json.dump writes the list of dictionaries to a JSON file with pretty formatting (indent=4).

Notes:

  • The JSON output will be an array of objects.

  • Make sure your CSV file has headers for proper key mapping.

  • For large files, you might want to process and write line-by-line or use streaming libraries.

Would you like a version that reads the CSV and outputs JSON as a string instead of writing to a file?

Share this Page your favorite way: Click any app below to share.

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Categories We Write About