Я новичок и новичок в сообществе.Я пытаюсь прочитать данные из файла Excel и преобразовать содержимое файла в формат JSON.Я знаю, что в прошлом у StackOverflow были вопросы о подобных вещах - с помощью этих вопросов мне удалось найти решение, но оно не сработало так, как ожидалось.
Вот как выглядит файл Excel:
![enter image description here](https://i.stack.imgur.com/gs8YY.png)
Вот как выглядит JSON:
{"linesOfFruits": [
{
"title" : {
"en": "Apple"
},
"url" : "https://isThisApple/123123"
},
{
"title" : {
"en": "Banana"
},
"teams" : [
{
"title" : {
"en": "Red Banana"
},
"url" : "https://isThisBanana/123124"
},
{
"title" : {
"en": "Green Banana"
},
"url" : "https://isThisBanana/123125"
},
{
"title" : {
"en": "Yellow Banana"
},
"url" : "https://isThisBanana/123126"
},
]
},
{
"title" : {
"en": "Grape"
},
"teams" : [
{
"title" : {
"en": "Orange Grape"
},
"url" : "https:/isThisGrape/1234"
},
{
"title" : {
"en": "Blue Grape"
},
"url" : "https:/isThisGrape/1235"
},
{
"title" : {
"en": "Pink Grape"
},
"url" : "https:/isThisGrape/1236"
},
]
}
]}
Однако, это то, что распечатывает мой код:
{"linesOfBusiness":
[
{
"title": "Apple",
"url": "https://isThisApple/123123"
},
{
"title": "Banana",
"teams": ["Orange Grape", "Blue Grape", "Pink Grape"],
"url": "https://isThisBanana/123124"
},
{
"title": "Grape",
"teams": ["Orange Grape", "Blue Grape", "Pink Grape"],
"url": "https:/isThisGrape/1234"}
]
}
Также обратите внимание, что если поле команды имеет значение (Все), то массив команд может быть опущен в JSON
Это то, что я имею до сих пор:
import json
import sys
import xlrd
def convertToJson(excelFile, sheetName, jsonFile):
workbook = xlrd.open_workbook(excelFile)
worksheet = workbook.sheet_by_name(sheetName)
data = []
keys = ['title', 'teams', 'url']
teams = []
for row_number in range(worksheet.nrows):
if row_number == 0:
continue
row_data = {}
empty = False
team = {}
list = worksheet.row(0)
for col_number, cell in enumerate(worksheet.row(row_number)):
if col_number == 0 and cell.value == '':
empty = True
elif col_number == 0:
empty = False
teams.clear()
if col_number == 1 and ( empty is True or cell.value != '(All)'):
team[keys[0]] = worksheet.row(row_number)
teams.append(cell.value)
print(teams)
elif col_number == 1 and cell.value == '(All)':
continue
# skip the number of fruits since it does not have to be in JSON file
if (col_number == 3):
continue
if col_number == 1:
if teams.__len__() > 0:
row_data[keys[col_number]] = teams
elif col_number == 0 and cell.value == '':
continue
else:
row_data[keys[col_number]] = cell.value
if 'title' in row_data:
data.append(row_data)
with open(jsonFile, 'w') as json_file:
json_file.write(json.dumps({
'linesOfBusiness': data
}))
Любая помощь будет принята с благодарностью.Застрял на этом какое-то время:)