Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Official Blog
  • Nearby Places Finder
  • Direction Route Finder
  • Distance & Time Calculator
Menu

Python 3 Script to Convert CSV File to Nested JSON Object and Save it inside JSON File

Posted on January 7, 2023

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

 

 

Python
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

 

 

 

Recent Posts

  • Angular 14/15 JWT Login & Registration Auth System in Node.js & Express Using MongoDB in Browser
  • Build a JWT Login & Registration Auth System in Node.js & Express Using MongoDB in Browser
  • React-Admin Example to Create CRUD REST API Using JSON-Server Library in Browser Using Javascript
  • Javascript Papaparse Example to Parse CSV Files and Export to JSON File and Download it as Attachment
  • Javascript Select2.js Example to Display Single & Multi-Select Dropdown & Fetch Remote Data Using Ajax in Dropdown
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme