c# .net Adsense ADO.NET Linq Viruses/security asp.net MVC JQuery Angular-js Node-js SEO Java C++ SQL API Networking vb.net .Net Css JavaScript Generics c#.Net entity framework HTML Website host Website Construction Guide HTTP tutorial W3C tutorial Web Services JSON Psychology Ionic framework Angular ReactJS Python Computer Android
Python

How to convert csv file to Json file in Python?

| | python

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 csv
import json

jsonArr = []

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:


json file generated