以递归方式循环遍历Python中的JSON输出

时间:2015-08-11 18:27:48

标签: python json loops while-loop

我有以下json输出:

{  
   "code":0,
   "message":"success",
   "data":[  
      {  
         "group_id":"12345678901234567890",
         "display_name":"GROUP",
         "description":"Group 1",
         "monitors":[  
            "12345678901234567890",
            "12345678901234567890",
            "12345678901234567890"
         ]
      },
      {  
         "group_id":"12345678901234567890",
         "display_name":"KK-GROUP1",
         "description":"KK Group 1",
         "monitors":[  
            "12345678901234567890",
            "12345678901234567890",
            "12345678901234567890"
         ]
      },
      {  
         "group_id":"12345678901234567890",
         "display_name":"KK-GROUP2",
         "description":"KK Group 2",
         "monitors":[  
            "12345678901234567890",
            "12345678901234567890",
            "12345678901234567890"
         ]
      },
      {  
         "group_id":"12345678901234567890",
         "display_name":"KK-GROUP3",
         "description":"KK Group 3",
         "monitors":[  
            "12345678901234567890",
            "12345678901234567890",
            "12345678901234567890"
         ]
      }
   ]
}

我有这个定义应循环通过从pycurl命令接收的JSON输出,并查找以KK开头的所有组,并从相应监视器字段中的所有ID创建一个列表以添加到我写的脚本的另一部分。在上面的输出中,它应该提供9个ID(每组3个)......无论出于何种原因,它只能获取前3个监视器ID。

def ReturnedMonitors():
    listOfChecks = json.loads(connectSite('GET',''))
    for i in listOfChecks['data']:
        while i['display_name'].startswith(options.clusterName.upper()):
            return i['monitors']

此输出将传递到以下内容:

for monitor in ReturnedMonitors():
          putData = 'activate/' + monitor
          print "Activated: " + modifyMonitors('PUT',putData)

modifyMonitors是另一个将发布到网站的pycurl定义。

1 个答案:

答案 0 :(得分:0)

如果您尝试使用 - ReturnedMonitors()创建生成器函数,则表示错误地创建了它,当您从函数返回return时,您需要使用yield关键字,同样,如果你需要单独在`monitor list中产生每个id,你应该循环它们并单独产生。示例 -

def ReturnedMonitors():
    listOfChecks = json.loads(connectSite('GET',''))
    for i in listOfChecks['data']:
        while i['display_name'].startswith(options.clusterName.upper()):
            for x in i['monitors']:
                yield x

对于Python 3.3 +,您可以使用yield from从迭代/迭代器中获取所有值(称为生成器委托) -

def ReturnedMonitors():
    listOfChecks = json.loads(connectSite('GET',''))
    for i in listOfChecks['data']:
        while i['display_name'].startswith(options.clusterName.upper()):
            yield from i['monitors']