forked from DhanushNehru/Python-Scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson_to_csv_with_nested_dict.py
59 lines (48 loc) · 1.53 KB
/
json_to_csv_with_nested_dict.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import json
import csv
def json_to_csv(json_data, csv_file, mapping=None):
if isinstance(json_data, list):
# Flatten nested JSON structures.
json_data = [flatten_json(obj) for obj in json_data]
# Get the column headers from the mapping or from the JSON data itself.
column_headers = mapping or json_data[0].keys()
# Write the CSV file.
with open(csv_file, "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(column_headers)
for row in json_data:
# Convert nested values to strings.
row_values = [str(row.get(column, "")) for column in column_headers]
writer.writerow(row_values)
def flatten_json(obj):
flattened = {}
for key, value in obj.items():
if isinstance(value, dict):
flattened.update(flatten_json(value))
elif isinstance(value, list):
for item in value:
flattened["{}.{}".format(key, item)] = item
else:
flattened[key] = value
return flattened
# sample mapping if needed
mapping = {
"name": "Name",
"status": "Status",
"date": "Date",
"author": "Author",
"probability": "Probability",
"result": "Result",
"final_status": "Final Status",
"connected.run_again": "Run Again",
"connected.next_test": "Next Test",
"connected.next_test_status": "Next Test Status"
}
def main():
# Load the JSON data.
with open("json_data.json", "r") as json_file:
json_data = json.load(json_file)
# Convert the JSON data to CSV format.
json_to_csv(json_data, "csv_data.csv")
if __name__ == "__main__":
main()