import json
import csv

"""
    Get nested data
"""
def get_leaves(item, key=None):
    if isinstance(item, dict):
        leaves = {}
        for i in item.keys():
            leaves.update(get_leaves(item[i], i))
            
        return leaves
    elif isinstance(item, list):
        leaves = {}
        for i in item:
            leaves.update(get_leaves(i, key))
            
        return leaves
    else:
        return {key : item}

file_name = 'investor-alert-list.json'
with open(file_name) as f_input:
    json_data = json.load(f_input)

# Parse all entries to get complete fieldname list
fieldnames = set()
for entry in json_data:
    fieldnames.update(get_leaves(entry).keys())

with open('moneysmart_dataset.csv', 'w', newline='') as f_output:
    csv_output = csv.DictWriter(f_output, fieldnames)
    csv_output.writeheader()
    csv_output.writerows(get_leaves(entry) for entry in json_data)
