我正在尝试从XLS文件数据更新json文件。 这就是我想做的:
我的问题是,当它为true时,如何更新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]
答案 0 :(得分:0)
当您将json数据从文件加载到内存时,它将变成一个名为“ json_intents_data”的python字典。
当条件“如果intentJsonNames中的nameXlsValue为True”时,您需要使用从Excel中读取的数据来更新字典。 (看来您知道该怎么做。)
完成“针对xrange(sheet.nrows)中的row_index:”循环后,您的字典将更新,您想将其保存为json文件。
L123