I am trying to create a script that parse json to csv format . I have created a script in python that works well only if only all the keys are present in the object. if some keys are not available in some object than code is breaking. if i add try catch than the script skipping the feild value instead of creating empty value for the same key if not present.

The Below script is not working for the below json as in that json first\_name and last\_name .. etc contains not present in other list or dict only present at first index. json as below on below path

<https://github.com/david8981/sample-data/blob/main/data1.json>

The below is the python code

```
import json
import csv

def parse_from_list(json_list, output_path):
    # Grab field names
    field_names = []
    for key in json_list[0].keys():
        current_key_list = set()
        found_list = False
        for obj in json_list:
            if isinstance(obj[key], dict):
                found_list = True
                for subkey in obj[key]:
                    current_key_list.add(subkey)
        if found_list:
            field_names.extend(['%s|||---|||%s' % (key, x) for x in list(current_key_list)])
        else:
            field_names.append(key)

    # Loop through objects and grab out data
    json_data = []
    for obj in json_list:
        new_data = {}
        for field in field_names:
            new_value = ''
            if '|||---|||' in field:
                if field.split('|||---|||')[0] in obj and field.split('|||---|||')[1] in obj[field.split('|||---|||')[0]]:
                    new_value = obj[field.split('|||---|||')[0]][field.split('|||---|||')[1]]
            else:
                if field in obj:
                    new_value = obj[field]
            new_data[field.replace('|||---|||', '_')] = new_value
        json_data.append(new_data)

    keys = json_data[0].keys()

    with open(output_path, 'w', newline='') as output_file:
        dict_writer = csv.DictWriter(output_file, keys)
        dict_writer.writeheader()
        dict_writer.writerows(json_data)
    pass

parse_from_list(json.load(open('data.json', 'rb'))['data']['items'], 'output.csv')

```

The code is working fine for below json

<https://github.com/david8981/sample-data/blob/main/data2.json>