I am trying to normalize/tabulate the multilevel data in JSON using Python Pandas.
Json data
{
"continent": "Asia",
"countries": [
{
"total" : "28",
"country": [
{
"name": "japan",
"economy": {
"business": "25%",
"jobs": "50%",
"government": "25%"
},
"population": [
{
"test1": "20L",
"test2": "15L"
}
]
},
{
"name": "china",
"economy": {
"business": "35%",
"jobs": "30%",
"government": "35%"
},
"population": [
{
"test1": "30L"
}
]
}
]
}
]
}
Required Output
| Country_name | Economy_type | Percentage_economy |
|---|---|---|
| Japan | Business | 25% |
| Japan | Jobs | 50% |
| Japan | Government | 25% |
| China | Business | 35% |
| China | Jobs | 30% |
| China | Government | 35% |
and
| Country_name | Population type | Percentage |
|---|---|---|
| Japan | test1 | 20L |
| Japan | test2 | 15L |
| China | test1 | 30L |
What I have tried
I've tried using pandas json_normalizer , flat_json and tried below code:
import json
import pandas as pd
with open('test.json') as f:
d = json.load(f)
dataFrame = pd.DataFrame(columns=d[0].keys())
for i in range(len(d)):
dataFrame.loc[i] = d[i].values()
print(dataFrame)
However, I'm not getting the desired output. I'm seeing an error:
KeyError: 0
or
| name | population | ... | economy.government | total | |
|---|---|---|---|---|---|
| 0 | japan | [{'test1': '20L', 'test2': '15L'}] | ... | 25% | 28 |
| 1 | china | [{'test1': '30L'}] | ... | 35% | 28 |