从嵌套的json文件中删除python dict项目

问题描述:

我有一个JSON文件,我尝试从python字典中删除项目时从返回KeyError:0的API中获取.我认为这是我缺乏技巧和json格式的结合.

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.

我的目标是从ip_address_1

我的代码:

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)

示例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",
 }
}

这是错误的:

# remove items
for i in xrange(len(obj)):
    if obj[i]["ip_address_1"] == "192.168.1.1":
        obj.pop(i)

您正在遍历一个对象,就好像它是一个列表一样.

You are iterating over an object as if it were a list.

您想做什么:

for sub_obj in obj["response"]["alerts"]:
    if sub_obj["ip_address_1"] == "192.168.1.1":
        sub_obj.pop("ip_address_1")