How to Convert a json file to a csv file in python

0

In python, everything is just as simple as you can think of. In this simple python project, you will see how you can create a python project that will take a JSON file as an input and output a CSV file.

Convert a json file to a csv file in python

We are not going to re-invent the wheel but we will use the JSON module and the CSV module. The json module and the CSV module are two built-in modules in python programming.

Create a file with the name app.py and paste the following code in it and then run it. It will convert a JSON file to a CSV file.



import json

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)}')

Just make sure that you have the json file in the current directory. It will then convert the json file into a csv file.

Summary and Conclusion

In this short tutorial, you have learned how you can convert a JSON file to a csv file in python. If you have any questions please let me know in the comment section.

Post a Comment

0Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !