我有大量的JSON数据,我想执行一些任务。所以我选择熊猫来做这个。
我有这样一个嵌套的json:
json_data = [
{
"item": "Item1",
"lowestPrice": {
"price": 11.00,
"currency": "EUR",
},
},
{
"item": "Item2",
"lowestPrice": {
"price": 12.00,
"currency": "EUR",
}
},
{
"item": "Item3",
"lowestPrice": {
"price": 13.00,
"currency": "EUR",
}
}
]我使用json_normalize()来规范嵌套的json,如:
df = pd.json_normalize(json_data, max_level=2)
item lowestPrice.price lowestPrice.currency
0 Item1 11.0 EUR
1 Item2 12.0 EUR
2 Item3 13.0 EUR
#do something现在,我需要将数据作为嵌套的JSON或dict返回:
json_data = [
{
"item": "Item1",
"lowestPrice": {
"price": 11.00,
"currency": "EUR",
},
"annotatePrice": 15.00
},
{
"item": "Item2",
"lowestPrice": {
"price": 12.00,
"currency": "EUR",
},
"annotatePrice": 15.00
},
{
"item": "Item3",
"lowestPrice": {
"price": 13.00,
"currency": "EUR",
},
"annotatePrice": 15.00
}
]发布于 2022-01-24 10:40:02
首先,我将列annotatePrice添加到dataframe。然后为lowestPrice构造内部字典,然后构造外部字典。我从这个stack answer中获得了我的解决方案。
下面是添加annotatePrice列后的数据。

转换代码:
df = pd.json_normalize(json_data, max_level=2)
df['annotatePrice'] = 15
json_data = (df.groupby(['item', 'annotatePrice'])
.apply(lambda x: x[['lowestPrice.price', 'lowestPrice.currency']].rename(columns={"lowestPrice.price":'price', "lowestPrice.currency":'currency'}).to_dict('records')[0])
.reset_index()
.rename(columns={0:'lowestPrice'})
.to_dict(orient='records'))
json_data输出:
[
{
'annotatePrice': 15,
'item': 'Item1',
'lowestPrice': {
'currency': 'EUR',
'price': 11.0
}
},
{
'annotatePrice': 15,
'item': 'Item2',
'lowestPrice': {
'currency': 'EUR',
'price': 12.0
}
},
{
'annotatePrice': 15,
'item': 'Item3',
'lowestPrice': {
'currency': 'EUR',
'price': 13.0
}
}
]https://stackoverflow.com/questions/70832010
复制相似问题