diff --git a/projects/Convert_JSON_to_CSV/converter.py b/projects/Convert_JSON_to_CSV/converter.py index 2b4a5fed..5ac618c0 100644 --- a/projects/Convert_JSON_to_CSV/converter.py +++ b/projects/Convert_JSON_to_CSV/converter.py @@ -1,15 +1,29 @@ import json +import csv -if __name__ == '__main__': - try: - with open('input.json', 'r') as f: - data = json.loads(f.read()) +# Open the JSON file and save the data as a variable. +with open('input.json') as f: + data = json.load(f) # Originally I used loads, but that caused a type error. Loads converts the data in memory + +familyData = data["data_file"] - output = ','.join([*data[0]]) - for obj in data: - output += f'\n{obj["Name"]},{obj["age"]},{obj["birthyear"]}' +# Create a file for writing +writeFile = open('output.csv', 'w') - with open('output.csv', 'w') as f: - f.write(output) - except Exception as ex: - print(f'Error: {str(ex)}') +# CSV writer object +csvWriter = csv.writer(writeFile) + +# Counter used for headers +count = 0 + +for name in familyData: + if count == 0: + + # Creates the initial headers using the first object + header = name.keys() + csvWriter.writerow(header) + count += 1 + + csvWriter.writerow(name.values()) + +writeFile.close()