Skip to content Skip to sidebar Skip to footer

Convert Nested Json To Csv In Python 2.7

Have seen a lot of thread but unable to found the solution for mine. I want to convert one nested JSON to CSV in Python 2.7. The sample JSON file is as below: sample.json # My JSON

Solution 1:

You're pretty much there. You're just calling csv_output.writerow() on the list you created with [v for k, v in leaf_entries]. You should instead call csv_output.writerows().

Information on these calls is available here: https://docs.python.org/3/library/csv.html#writer-objects

Solution 2:

Just figured it out. The below code properly working and generating valid csv data from my complex JSON file.

# Generate CSV from JSON
fw_access_layers_data = open('show-access-layers.json', 'r')
fw_access_layers_parsed = json.loads(fw_access_layers_data.read())
access_layers = fw_access_layers_parsed['access-layers']
fw_access_layers_csv = open('show-access-layers.csv', 'w')
csvwriter = csv.writer(fw_access_layers_csv)
count = 0for access_layer in access_layers:
if count == 0:
    header = access_layer.keys()
    csvwriter.writerow(header)
    count += 1
csvwriter.writerow(access_layer.values())
fw_access_layers_csv.close()

Thanks for your help mates.

Post a Comment for "Convert Nested Json To Csv In Python 2.7"