I have the following json data:
hostcreate = {
"jsonrpc": "2.0",
"method": "host.create",
"params": {
"host": "my_host",
"port": 10050,
"interfaces": [{
"type": 1,
"main": 1,
"useip": 1,
"ip": "10.100.200.200",
"dns": "",
"port": "10050"
}],
"groups": [{
"groupid": 2
}, {
"groupid": 22
}]
},
"auth": "byese31blahblah",
"id": 1
}
I can update the values of existing keys with something like this:
hostcreate['params']['port'] = str(newhostport)
However, when I try to add a new key/value to the dictionary, I get an error:
hostcreate['params']['groups'][count]['groupid'] = int(eachgroupid)
IndexError: list index out of range
I'm getting that error when the value of count is greater than the number of available slots for groupid. So in other words, right now, groupid has 2 slots, which I can update easily. But when I try to add a new key/value for groupid, I get the aforementioned error.
How can I resolve this?
UPDATE:
Here's the code (which isn't working):
numofgroups = len(groupids.split(","))
rnumofgroups = numofgroups - 1
count = 0
existinggids = len(hostcreate['params']['groups']) - 1
while (count <= numofgroups):
eachgroupid = groupids.split(",")[count]
if count <= existinggids:
count = count + 1
hostcreate['params']['groups'][count]['groupid'] = int(eachgroupid)
else:
count = count + 1
hostcreate['params'['groups'].append({
'groupid':int(eachgroupid)
})
every time I run this, it keeps complaining. can anyone spot what is wrong with my code?