I would like to convert a JSON to Pandas dataframe.
My JSON looks like: like:
{
\"country1\":{
\"AdUnit1\":{
\"floor_price1\":{
Not the best way, but it's work. Also you should modify flatten function that is only picked from this awnser
test = {
"country1":{
"AdUnit1":{
"floor_price1":{
"feature1":1111,
"feature2":1112
},
"floor_price2":{
"feature1":1121
}
},
"AdUnit2":{
"floor_price1":{
"feature1":1211
},
"floor_price2":{
"feature1":1221
}
}
},
"country2":{
"AdUnit1":{
"floor_price1":{
"feature1":2111,
"feature2":2112
}
}
}
}
from collections import defaultdict
import pandas as pd
import collections
def flatten(d, parent_key='', sep='_'):
items = []
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
if isinstance(v, collections.MutableMapping):
items.extend(flatten(v, new_key, sep=sep).items())
else:
items.append((new_key, v))
return dict(items)
results = defaultdict(list)
colnames = ["col1", "col2", "col3", "col4", "col5", "col6"]
for key, value in flatten(test).items():
elements = key.split("_")
elements.append(value)
for colname, element in zip(colnames, elements):
results[colname].append(element)
df = pd.DataFrame(results)
print(df)