Обновите файл json из данных файла XLS - PullRequest
0 голосов
/ 12 мая 2019

Я пытаюсь обновить файл json из данных файла XLS. Вот что я хочу сделать:

  • Извлечение имен из Джона
  • Извлечение имен из XLS
  • для nameFromXLS в именах FromXLS:
    • Проверьте, находится ли nameFromXLS в namesFromJson:
      • если истина: тогда:
        • извлечь строку xls (с таким именем)
        • обновить jsonFile (с таким именем)

Моя проблема в том, когда это правда, как я могу обновить jsonfile?

Python code:

    import xlrd
    import unicodedata
    import json

    intents_file = open("C:\myJsonFile.json","rU")
    json_intents_data = json.load(intents_file)

    book = xlrd.open_workbook("C:\myXLSFile.xlsx")
    sheet = book.sheet_by_index(0)
    row =""
    nameXlsValues = []
    intentJsonNames =[]

    for entity in json_intents_data["intents"]: 
        intentJsonName = entity["name"]
        intentJsonNames.append(intentJsonName)

    for row_index in xrange(sheet.nrows):
        nameXlsValue = sheet.cell(rowx = row_index,colx=0).value
        nameXlsValues.append(nameXlsValue)

        if nameXlsValue  in intentJsonNames:
           #here ,I have to extract row values from xlsFile and update jsonFile 
           for col_index in xrange(sheet.ncols):
               value = sheet.cell(rowx = row_index,colx=col_index).value
               if type(value) is unicode:
                     value = unicodedata.normalize('NFKD',value).encode('ascii','ignore')
                      row += "{0} - ".format(value)

my json file  is like this : 
{
 "intents": [
        {
            "id": "id1",
            "name": "name1",
            "details": {
                "tags": [
                    "tag1"
                ],
                "answers": [
                    {
                        "type": "switch",
                        "cases": [
                             {
                                "case": "case1",
                                "answers": [
                                    {
                                        "tips": [
                                            ""
                                        ],
                                        "texts": [
                                            "my text to be updated"
                                        ]
                                    }
                                ]
                            },
                            {
                                "case": "case2",
                                "answers": [
                                    {
                                        "tips": [
                                            "tip2"
                                        ],
                                        "texts": [
                                        ]
                                    }
                                ]
                            }
                        ]
                    }
                ],
                "template": "json",
                "sentences": [
                    "sentence1",
                    " sentence2",
                    " sentence44"]
            }
        },
        {
            "id": "id2",
            "name": "name3",
            "details": {
                "tags": [
                    "tag2"
                ],
                "answers": [
                    {
                        "type": "switch",
                        "cases": [
                            {
                                "case": "case1",
                                "answers": [
                                    {
                                        "texts": [
                                          ""
                                        ]             
                                    }
                                ]
                            },
                            {
                                "case": "case2",
                                "answers": [
                                    {
                                        "texts": [
                                            ""
                                        ]
                                    }
                                ]
                            }
                        ]
                    }
                ],
                "sentences": [
                    "sentence44",
                    "sentence2"
                ]
            }
        }
    ]   
}   

Мой xls файл выглядит так:

[![enter image description here][1]][1]

enter image description here

1 Ответ

0 голосов
/ 13 мая 2019

Когда вы загружаете данные json из файла в память, они превращаются в python dict с именем 'json_intents_data'.

Когда условие 'if nameXlsValue в intentJsonNames' имеет значение True, вам нужно обновить dict данными, которые вы читаете из Excel.(Похоже, вы знаете, как это сделать.)

Когда цикл 'для row_index в xrange (sheet.nrows):' завершен, ваш dict обновляется, и вы хотите сохранить его как файл json.

import json

with open('updated_data.json', 'w') as fp:
    json.dump(json_intents_data, fp) 
...