In this tutorial I will show you how to convert csv to json in python.
To convert csv to json:
we have to import csv and json packages. Use csv.DictReader() to read the lines of the csv file and then add to the array. To convert object to the JSON string using json.dumps() and write to JSON String to json file.
CODE:
import csvimport jsonjsonArr = []with open('shampoo_sales.csv', encoding='utf-8') as csvfile:csvReader = csv.DictReader(csvfile)for row in csvReader:jsonArr.append(row)with open('shampoo_sales.json', 'w', encoding='utf-8') as jsonfile:jsonString = json.dumps(jsonArr, indent=4)jsonfile.write(jsonString)
OUTPUT:
Post your comments / questions
Recent Article
- How to hide the ID field from the Django admin?
- It is impossible to add a non nullable field without specifying a default. Django error
- ImportError: cannot import name 'url' from 'django.conf.urls' - Django Error
- How to Enable Virtualization in BIOS Security Settings in Intel Processors For Android Studio?
- Dependency 'androidx.activity:activity:1.8.0' requires libraries and applications that depend on it.
- AttributeError: 'NoneType' object has no attribute 'get_text' - Python
- ModuleNotFoundError: No module named 'openpyxl' - Python
- How to get thumbnail from vimeo video URL in Python?
Related Article