-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvert_json_to_csv.py
More file actions
86 lines (76 loc) · 2.56 KB
/
convert_json_to_csv.py
File metadata and controls
86 lines (76 loc) · 2.56 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import json
import pandas as pd
def flatten_json(y, parent_key='', sep='_'):
"""Recursive function to flatten a JSON object."""
items = []
if isinstance(y, dict):
for k, v in y.items():
new_key = f"{parent_key}{sep}{k}" if parent_key else k
items.extend(flatten_json(v, new_key, sep=sep).items())
elif isinstance(y, list):
for i, v in enumerate(y):
new_key = f"{parent_key}{sep}{i}" if parent_key else str(i)
items.extend(flatten_json(v, new_key, sep=sep).items())
else:
items.append((parent_key, y))
return dict(items)
def json_to_csv(json_string, output_csv):
"""Converts a JSON string to a CSV file."""
try:
data = json.loads(json_string)
# Check if the JSON data is a list, if not, make it a list
if not isinstance(data, list):
data = [data]
# Flatten each JSON object
flattened_data = [flatten_json(item) for item in data]
# Convert JSON to DataFrame
df = pd.DataFrame(flattened_data)
df.to_csv(output_csv, index=False)
print(f"Conversion completed. The CSV file has been saved as '{output_csv}'.")
except json.JSONDecodeError as e:
print(f"Invalid JSON data: {e}")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
# Example of reading a JSON string from standard input
json_string = '''
{
"problems": [{
"Diabetes":[{
"medications":[{
"medicationsClasses":[{
"className":[{
"associatedDrug":[{
"name":"asprin",
"dose":"",
"strength":"500 mg"
}],
"associatedDrug#2":[{
"name":"somethingElse",
"dose":"",
"strength":"500 mg"
}]
}],
"className2":[{
"associatedDrug":[{
"name":"asprin",
"dose":"",
"strength":"500 mg"
}],
"associatedDrug#2":[{
"name":"somethingElse",
"dose":"",
"strength":"500 mg"
}]
}]
}]
}],
"labs":[{
"missing_field": "missing_value"
}]
}],
"Asthma":[{}]
}]}
'''
output_csv = "data.csv"
json_to_csv(json_string, output_csv)