[英]How to convert an excel to a nested JSON using xlrd?
我是 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
我想要以下格式的 output:
[
"brand": "C",
"devices":
[
{
"device_model": "modelA",
"object_code" : "0x3",
"part_numbers": [
"09823",
"08334"
]
},
{
"device_model": "modelB",
"object_code" : "0x7",
"part_numbers": [
"98223"
]
}
]
这是我的代码:
def 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)
该代码的output为:
[
{
"brand": "C",
"devices": [
{
"object_code": "0x3",
"device_model": "modelA",
"part_numbers": [
{
"": "09823"
},
{
"": "08334"
}
]
},
{
"object_code": "0x7",
"device_model": "modelB",
"part_numbers": [
{
"": "09223"
}
]
}
}
]
}
]
我认为我需要将“部件号”和 append 分开给我的 Jason。 我试过了,但我没有得到我想要的 output。
我会使用 pandas 来解决这个问题。 您可以像这样轻松转换它。
dataframe = pd.read_excel("myFilee.xls") dataframe.to_json('json_output.json', index=False)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.