需要从json字段和数组生成CSV文件.
JSON文件包含一个字段和一个array.我需要创建一个CSV文件,其中一个作为字段,另一个具有从数组中检索的值.
输入:
{
"Emp": {
"EmpID": SE451,
"EMpName": "Vincent",
"Leaves": [
{
"leave": 2
},
{
"leave": 1
}
]
}
expectedCSV应该是这样的,
E_name | E_leaves |
---|---|
Vincent | 2 |
1 |
为此,我try 使用下面的代码,但它不能像预期的那样工作.
Fl_content = []
dat_content=[]
emp_ids = ('E_name','E_Leaves')
hdr = ','.join(emp_ids)
for ar in json_data['Emp']['Leaves']:
Fl_content.append(str(ar['leave']))
leave_data = '\n'.join(Fl_content)
leave_with_header = json_data['Emp']['EmpName'], leave_data
dat3 = ','.join(leave_with_header)
#print(dat3)
hdr+'\n'+dat3
我得到的CSV字符串是E_name,E_leaves\nVinent,2\n1
我的CSV文件如下所示(这是意想不到的),
E_name | E_leaves |
---|---|
Vincent | 2 |
1 |
注:我正在使用云函数上传GCS存储桶中的CSV. 因此,我想使用CSV字符串概念来实现这一点.
帮助我实现上面所说的预期目标.