【发布时间】:2020-03-25 07:48:00
【问题描述】:
我是 Python 编程新手,我正在尝试编写一个读取 xlxs 文件并将其转换为 json 的程序。 (我一直在使用 Python 3 和 Jupyter Notebook,但我遇到了一些问题和困难。)
============================
我的 xlsx 文件中有两行四列:
id label id_customer label_customer
6 Sao Paulo CUST-99992 Brazil
92 Hong Hong CUST-88888 China
============================
这是我的代码:
import pandas as pd
import json
file_imported = pd.read_excel('testing.xlsx', sheet_name = 'Plan1')
list1 = []
list = []
for index, row in file_imported.iterrows():
list.append ({
"id" : int(row['id']),
"label" : str(row['label']),
"Customer" : list1
})
list1.append ({
"id" : str(row['id_customer']) ,
"label" : str(row['label_customer'])
})
print (list)
with open ('testing.json', 'w') as f:
json.dump(list, f, indent= True)
==========================
Json 输出:
[
{
"id": 6,
"label": "Sao Paulo",
"Customer": [
{
"id": "CUST-99992",
"label": "Brazil"
},
{
"id": "CUST-88888",
"label": "China"
}
]
},
{
"id": 92,
"label": "Hong Hong",
"Customer": [
{
"id": "CUST-99992",
"label": "Brazil"
},
{
"id": "CUST-88888",
"label": "China"
}
]
}
]
==========================
预期结果:
[
{
"id": 6,
"label": "Sao Paulo",
"Customer": [
{
"id": "CUST-99992",
"label": "Brazil"
}
]
},
{
"id": 92,
"label": "Hong Hong",
"Customer": [
{
"id": "CUST-88888",
"label": "China"
}
]
}
]
==========================
谁能帮帮我?
【问题讨论】:
标签: python json excel pandas jupyter-notebook