This script takes a JSON file as input and generates a CSV file in output.
Prerequisites Modules:
- json
- Run
pip install json
to install required external modules.
How to run the script
- Execute
python3 converter.py
Source Code:
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)}')
Input:
[
{
"Name": "Akash",
"age": 26,
"birthyear": "1994"
},
{
"Name": "Abhay",
"age": 34,
"birthyear": "1986"
}
]
Code language: JSON / JSON with Comments (json)
Output:
1 | Name | age | birthyear |
---|---|---|---|
2 | Akash | 26 | 1994 |
3 | Abhay | 34 | 1986 |