Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 7fd43a8

Browse files
authored
Update Unnestjson.py
1 parent 776929c commit 7fd43a8

File tree

1 file changed

+24
-14
lines changed

1 file changed

+24
-14
lines changed

Unnestjson.py

Lines changed: 24 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,33 @@
11
import json
22
import pandas as pd
3-
from pandas import json_normalize
43

5-
# Load JSON from file or string
4+
# Recursive function to flatten nested JSON
5+
def flatten(obj, parent_key='', sep='.'):
6+
items = []
7+
if isinstance(obj, dict):
8+
for k, v in obj.items():
9+
new_key = f"{parent_key}{sep}{k}" if parent_key else k
10+
items.extend(flatten(v, new_key, sep=sep).items())
11+
elif isinstance(obj, list):
12+
for i, v in enumerate(obj):
13+
new_key = f"{parent_key}[{i}]"
14+
items.extend(flatten(v, new_key, sep=sep).items())
15+
else:
16+
items.append((parent_key, obj))
17+
return dict(items)
18+
19+
# Load JSON file
620
with open("input.json") as f:
7-
data = json.load(f)
21+
raw_data = json.load(f)
822

9-
# Flatten JSON
10-
def flatten_json(json_data):
11-
if isinstance(json_data, list):
12-
df = json_normalize(json_data)
13-
elif isinstance(json_data, dict):
14-
df = json_normalize([json_data])
15-
else:
16-
raise ValueError("Unsupported JSON format")
17-
return df
23+
# Handle list of records or single record
24+
if isinstance(raw_data, list):
25+
flat_data = [flatten(entry) for entry in raw_data]
26+
else:
27+
flat_data = [flatten(raw_data)]
1828

19-
# Unnest and convert to CSV
20-
df = flatten_json(data)
29+
# Convert to DataFrame
30+
df = pd.DataFrame(flat_data)
2131

2232
# Save to CSV
2333
df.to_csv("output.csv", index=False)

0 commit comments

Comments
 (0)