问题描述
我是 Python 新手,需要将 excel 文件转换为嵌套的 JSON。我正在使用 xlrd 库来解析 excel 文件。
我的 Excel 文件示例:
code number object code device Model brand
09823 0x3 modelA C
08334 0x3 modelA C
98223 0x7 modelB C
我想要以下格式的输出:
[
"brand": "C","devices":
[
{
"device_model": "modelA","object_code" : "0x3","part_numbers": [
"09823","08334"
]
},{
"device_model": "modelB","object_code" : "0x7","part_numbers": [
"98223"
]
}
]
这是我的代码:
定义 xlsParse(xlsfile): store = [] #要解析成json文件的对象列表 framenames = [] #这个列表帮助我们跟踪存储在我们的对象列表中的内容
book = xlrd.open_workbook("myFilee.xls")
sh1 = book.sheet_by_index(0)
for rx in range(1,sh1.nrows):
if sh1.row(rx)[14].value not in framenames:
framenames.append(sh1.row(rx)[14].value)
frame = {"brand": sh1.row(rx)[14].value,"devices":[]
}
store.append(frame)
segment = {"object_code":""}
for frame in store:
for rx in range(1,sh1.nrows):
if frame["brand"] == sh1.row(rx)[14].value:
if segment["object_code"] != sh1.row(rx)[12].value:
segment = {
"object_code": sh1.row(rx)[12].value,"device_model":sh1.row(rx)[13].value,"part_numbers":[{
"": sh1.row(rx)[3].value
}]
}
frame["devices"].append(segment)
else:
packet_partNumber = {
"" :sh1.row(rx)[3].value,}
segment["part_numbers"].append(packet_partNumber)
这段代码的输出是:
[
{
"brand": "C","devices": [
{
"object_code": "0x3","device_model": "modelA","part_numbers": [
{
"": "09823"
},{
"": "08334"
}
]
},{
"object_code": "0x7","device_model": "modelB","part_numbers": [
{
"": "09223"
}
]
}
}
]
}
]
我认为我需要将“零件编号”分开并将它们附加到我的 Jason。我试过了,但我无法得到我想要的输出。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)