I have a JSON file that I fetch from an API that returns KeyError:0 while I attempt to remove items in a python dict. I assume its a combination of my lack of skill and format of the json.
My goal is to remove all instances of 192.168.1.1 from ip_address_1
My Code:
from api import Request
import requests, json, ordereddict
# prepare request
request = Request().service('').where({"query":"192.168.1.0"}).withType("json")
# call request
response = request.execute()
# parse response into python object
obj = json.loads(response)
# remove items
for i in xrange(len(obj)):
if obj[i]["ip_address_1"] == "192.168.1.1":
obj.pop(i)
# display
print json.dumps(obj,indent=1)
Example JSON:
{
"response": {
"alerts": [
{
"action": "New",
"ip_address_1": "192.168.1.1",
"domain": "example.com",
"ip_address_2": "192.68.1.2"
},
{
"action": "New",
"ip_address_1": "192.168.1.3",
"domain": "example2.com",
"ip_address_2": "192.168.1.1"
}
],
"total": "2",
"query": "192.168.1.0",
}
}
[alert['ip_address_1'] for alert in obj['response']['alerts'] if alert['ip_address_1'] != '192.168.1.1']. Is that a correct interpretation of your question?