I would like to load some JSON data into a pandas dataframe. Normally, i would use pandas.json_normalize, but I would also like to enforce a scheme (columns and ideally also dtypes) regardless of whether all fields are found in the json documents.
So
one = [
{
"fruit": "apple",
"price": 2,
"color": "red"
},
{
"fruit": "banana",
"color": "yellow"
},
{
"fruit": "orange",
"color": "orange"
}
]
two = [
{
"fruit": "banana",
"color": "yellow"
},
{
"fruit": "orange",
"color": "orange"
}
]
pd.json_normalize(one)
pd.json_normalize(two)
returns
fruit price color
0 apple 2.0 red
1 banana NaN yellow
2 orange NaN orange
fruit color
0 banana yellow
1 orange orange
When I would like to have the price column in any case, either with NAs or some predefined value. Currently I am doing something like:
def load_fruits(json):
default_fruit = {
"fruit": "",
"color": "",
"price": 0
}
fruits = []
for item in json:
fruit = {
key: item[key]
if key in item.keys()
else default_fruit[key]
for key in default_fruit.keys()
}
fruits.append(fruit)
return pd.DataFrame(fruits)
But I was wondering if there was a more efficient way to handle this for larger datasets. Thanks!