Skip to content
This repository has been archived by the owner on May 25, 2022. It is now read-only.

Convert_JSON_to_CSV project re-written with the correct syntax. #595

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 25 additions & 11 deletions projects/Convert_JSON_to_CSV/converter.py
Original file line number Diff line number Diff line change
@@ -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()