-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson2csv.py
51 lines (32 loc) · 1.01 KB
/
json2csv.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/python3
import json
import pandas
def read_json(filename: str) -> dict:
try:
with open(filename, "r") as f:
data = json.loads(f.read())
except:
raise Exception(f"Reading {filename} file encountered an error")
return data
def create_dataframe(data: list) -> pandas.DataFrame:
# Declare an empty dataframe to append records
dataframe = pandas.DataFrame()
# Looping through each record
for d in data:
# Normalize the column levels
record = pandas.json_normalize(d)
# Append it to the dataframe
dataframe = dataframe.append(record, ignore_index=True)
return dataframe
def main():
# Read the JSON file as python dictionary
data = read_json(filename="0.json")
# Generate the dataframe for the array items in
# details key
dataframe = create_dataframe(data=data['results'])
# Renaming columns of the dataframe
print("Normalized Columns:", dataframe.columns.to_list())
# Convert dataframe to CSV
dataframe.to_csv("details.csv", index=False)
if __name__ == '__main__':
main()