Multiple relational tables to nested JSON format using Python(使用 Python 将多个关系表转换为嵌套的 JSON 格式)
问题描述
我正在尝试通过使用 python/pandas 组合多个关系表来创建嵌套的 JSON 对象.我是 Python/pandas 的初学者,所以在这里寻求帮助...
在下面的例子中,为了简单起见,我使用 CSV 文件而不是表格
<块引用>*所需输出:
<代码>{数据": [{员工":1,性别":M,年龄":32,激励": [{八月":3000,九月":3500,十月":2000}],雇员":2,性别":M,年龄":35,激励": [{八月":1500}],员工":3,性别":F,年龄":31,激励": [{八月":5000,九月":2400}]}]}
使用 merge
先用左连接,然后 groupby
带有用于字典的 lambda 函数并转换 to_dict
,最后添加顶部 key
值并转换为 json
:
d = (df1.merge(df2, on='Emp_id', how='left').groupby(['Emp_id','Gender','Age'])['Month','Incentive'].apply(lambda x: [dict(x.values)]).reset_index(name='Incentive').to_dict(orient='记录'))#打印(d)导入jsonjson = json.dumps({'数据':d})
<小时>
print (json){数据": [{Emp_id":1,"性别": "M",年龄":32,激励": [{八月":3000,九月":3500,十月":2000}]}, {Emp_id":2,"性别": "M",年龄":35,激励": [{八月":1500}]}, {Emp_id":3,"性别": "F",年龄":31,激励": [{八月":5000,九月":2400}]}]}
I'm trying to create nested JSON object by combining more than one relational tables using python/pandas. I'm a beginner in Python/pandas, so looking for bit of a help here...
In the following example, instead of tables, I'm using CSV files just to keep it simple
*Requiredoutput:
{
"data": [{
"employee": 1,
"gender": M,
"age": 32,
"incentive": [{
"aug": 3000,
"sep": 3500,
"oct": 2000
}],
"employee": 2,
"gender": M,
"age": 35,
"incentive": [{
"aug": 1500
}],
"employee": 3,
"gender": F,
"age": 31,
"incentive": [{
"aug": 5000,
"sep": 2400
}]
}]
}
Use merge
with left join first, then groupby
with lambda function for dictionaries and convert to_dict
, last add top key
value and convert to json
:
d = (df1.merge(df2, on='Emp_id', how='left')
.groupby(['Emp_id','Gender','Age'])['Month','Incentive']
.apply(lambda x: [dict(x.values)])
.reset_index(name='Incentive')
.to_dict(orient='records')
)
#print (d)
import json
json = json.dumps({'data':d})
print (json)
{
"data": [{
"Emp_id": 1,
"Gender": "M",
"Age": 32,
"Incentive": [{
"Aug": 3000,
"Sep": 3500,
"Oct": 2000
}]
}, {
"Emp_id": 2,
"Gender": "M",
"Age": 35,
"Incentive": [{
"Aug": 1500
}]
}, {
"Emp_id": 3,
"Gender": "F",
"Age": 31,
"Incentive": [{
"Aug": 5000,
"Sep": 2400
}]
}]
}
这篇关于使用 Python 将多个关系表转换为嵌套的 JSON 格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!