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.
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
datalist. -
json.dumpwrites 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.