showing results for - "nested json to csv python"
Tim
09 Mar 2019
1import json
2import csv
3import requests
4
5response = requests.get('https://statsapi.web.nhl.com/api/v1/teams')
6json_data = response.json()
7
8def get_leaves(item, key=None):
9    if isinstance(item, dict):
10        leaves = {}
11        for i in item.keys():
12            leaves.update(get_leaves(item[i], i))
13        return leaves
14    elif isinstance(item, list):
15        leaves = {}
16        for i in item:
17            leaves.update(get_leaves(i, key))
18        return leaves
19    else:
20        return {key : item}
21
22# First parse all entries to get the complete fieldname list
23fieldnames = set()
24
25for entry in json_data:
26    fieldnames.update(get_leaves(entry).keys())
27
28with open('output.csv', 'w', newline='') as f_output:
29    csv_output = csv.DictWriter(f_output, fieldnames=sorted(fieldnames))
30    csv_output.writeheader()
31    csv_output.writerows(get_leaves(entry) for entry in json_data)
32