Load JSON file to
aPoollist at beginning.def LoadPoolTemplate(): sFilename = './pool_template.json' if os.path.exists(sFilename): with open(sFilename, 'r') as fJsonFile: aPool = json.load(fJsonFile) return aPoolAppend
aTempJsontoaPool[index]['devices']def UpdateJSON(aPool, aDevList): sFilename = './device_template.json' if os.path.exists(sFilename): with open(sFilename, 'r') as fJsonFile: aTempJson = json.load(fJsonFile) else: print ("No such file names " + sFilename) for item in aDevList: aTempJson['id'] = item[1] aTempJson['atti']['high'] = item[2] for (i,pid) in enumerate(aPool): if pid['id'] == item[0]: aPool[i]['devices'].append(aTempJson) breakUpdate
aPoollist to JSON filedef CreateDeviceJSON(aDevice): with open(gDevice, 'w') as fOutfile: json.dump(aDevice, fOutfile, indent=2)Read list
def ReadDeviceList(): aDevList = [] with open(gDevList, 'r') as fList: for line in fList: columns = line.strip().split(',') aDevList.append(columns) return aDevListmain function
def main(): aDevDist = [] aDeviceJson = [] aDeviceJson = LoadPoolTemplate() aDeviceList = ReadDeviceList() aDeviceJson = UpdateJSON(aDeviceJson, aDeviceList) CreateDeviceJSON(aDeviceJson)
I don't know why all the elements in devices list are the same, please help me.
JSON file output:
[
{
"id": "id1",
"devices": [
{
"atti": {
"high": "190",
"weight": "80"
},
"id": "Jordan"
},
{
"atti": {
"high": "190",
"weight": "80"
},
"id": "Jordan"
},
{
"atti": {
"high": "190",
"weight": "80"
},
"id": "Jordan"
}
]
},
{
"id": "id2",
"devices": [
{
"atti": {
"high": "190",
"weight": "80"
},
"id": "Jordan"
}
]
},
{
"id": "id3",
"devices": [
{
"atti": {
"high": "190",
"weight": "80"
},
"id": "Jordan"
}
]
}
]
Input source as following:
["id1", "apple", "167"]
["id1", "carter", "203"]
["id1", "jason", "188"]
["id2", "paul", "178"]
["id3", "Jordan", "190"]
Pool template
[
{
"id": "id1",
"devices": [
]
},
{
"id": "id2",
"devices": [
]
},
{
"id": "id3",
"devices": [
]
}
]