DEV Community

Harendra Kumar Kanojiya
Harendra Kumar Kanojiya

Posted on • Originally published at Medium on

Convert JSON to CSV — Python

Convert JSON to CSV — Python

A python script to convert JSON data to CSV file

This script will convert your JSON data to a CSV file. It takes .json a file as input and provides .csv the file as output.

Installation

pip install json
Enter fullscreen mode Exit fullscreen mode

Script

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["birthyear"]}'

        with open('output.csv', 'w') as f:
            f.write(output)
    except Exception as ex:
        print(f'Error: {str(ex)}')
Enter fullscreen mode Exit fullscreen mode

Thank you for reading this tutorial. Don’t forget to clap 👏 and follow me to read more articles like this in the future.


Discussion (0)