Untitled
unknown
python
2 years ago
1.7 kB
14
Indexable
import json
import csv
# Input JSON file name
json_file = 'input.json'
# Output flat file name (e.g., CSV)
output_file = 'output.csv'
def flatten_json(json_object, parent_key='', separator='_'):
"""
Recursively flatten a JSON object.
"""
items = {}
for key, value in json_object.items():
new_key = parent_key + separator + key if parent_key else key
if isinstance(value, dict):
items.update(flatten_json(value, new_key, separator=separator))
else:
items[new_key] = value
return items
try:
# Read JSON data from the input file
with open(json_file, 'r') as json_data:
data = json.load(json_data)
# Ensure the JSON data is a list of dictionaries
if not isinstance(data, list) or not all(isinstance(entry, dict) for entry in data):
raise ValueError("JSON data should be a list of dictionaries")
# Flatten the JSON data
flat_data = [flatten_json(entry) for entry in data]
# Extract field names from the flattened data
field_names = set()
for entry in flat_data:
field_names.update(entry.keys())
# Write the data to the flat file (CSV)
with open(output_file, 'w', newline='') as csv_file:
writer = csv.DictWriter(csv_file, fieldnames=sorted(field_names))
# Write the header row
writer.writeheader()
# Write each flattened dictionary as a row in the CSV file
for entry in flat_data:
writer.writerow(entry)
print(f"Data from '{json_file}' has been successfully written to '{output_file}'.")
except FileNotFoundError:
print(f"Error: File '{json_file}' not found.")
except Exception as e:
print(f"An error occurred: {str(e)}")
Editor is loading...