Python 3 Script to Convert JSON to CSV File Using json Module Full Project For Beginners
Welcome folks today in this post we will be converting json to csv
file using json
module in python. All the full source code of the application is given below.
Get Started
In order to get started we need to install the following library using the pip
command as shown below
pip install json
After installing this library make an app.py
file and copy paste the following code
app.py
import json
if __name__ == '__main__':
try:
with open('input.json', 'r') as f:
data = json.loads(f.read())
output = ','.join([*data[0]])
for obj in data:
output += f'\n{obj["name"]},{obj["age"]},{obj["subject"]}'
with open('output.csv', 'w') as f:
f.write(output)
except Exception as ex:
print(f'Error: {str(ex)}')
Now we need to make an input.json
file and copy paste the following code
input.json
[
{
"name": "gautam",
"age": 13,
"subject": "computer science"
},
{
"name": "gautam",
"age": 13,
"subject": "computer science"
},
{
"name": "gautam",
"age": 13,
"subject": "computer science"
},
{
"name": "gautam",
"age": 13,
"subject": "computer science"
}
]
Now if you execute the python
script by typing the below command
python app.py
After execution of the script it will create the output.csv
file inside the same directory as shown below