Welcome folks today in this blog post we will be converting csv
file to nested json
object and save it inside json
file. All the full source code of the application is shown below.
Get Started
In order to get started you need to make an app.py
file and copy paste the following code
app.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import csv import json # Open the CSV file f = open('output.csv', 'r') # Change each fieldname to the appropriate field name. I know, so difficult. reader = csv.DictReader(f, fieldnames = ("Name","Age","Country")) # Parse the CSV into JSON out = json.dumps([row for row in reader]) # Write the JSON object to a file with open("data.json", "w") as f: f.write(out) |
As you can see we are importing the csv
and json
module and then we are opening the output.csv
file contents inside the read
mode and then we are converting the csv
file to nested file json object using the DictReader()
method. And then we are dumping the data
inside the json
file using the for loop. And then we are opening the data.json
file to write the data inside it. And then inside it we are using the write()
method to write the data.
Now if you execute the python
script in the command line as shown below
python app.py