【发布时间】:2015-04-23 09:36:30
【问题描述】:
def getValueForSpecificKey(self,capturedLog,key):
''' Get value from log for any specific key,caputredLog must be a string'''
global Found
global returnValue
if type(capturedLog)==type({}):
for eachKey in capturedLog:
if eachKey==key:
Found=True
print "Found Key Match :",eachKey
print capturedLog[key]
listAppendValue=capturedLog[key]
#returnValue=capturedLog[key]
returnValue.append(listAppendValue)
print "="*1000
print "The value for key in the captured Log is -> ",capturedLog[key]
print " Return value "*10,(returnValue)
return Found,returnValue
self.getValueForSpecificKey(capturedLog[eachKey],key)
elif type(capturedLog) is list:
for elements in capturedLog:
self.getValueForSpecificKey(elements,key)
print returnValue
return Found,returnValue
我有这个函数,它递归迭代一个有效的 json。json 可能包含 dict 或 list。这里搜索的函数需要一些输入日志,它是 json 和一个在 json 中搜索的键。我能够迭代得到json 中的所有键。一切都很好。
但是当我尝试返回值时问题就来了。由于 returnValue 是一个全局变量。附加到列表中,继续将所有值附加到同一个列表中。即使我从一些创建类的对象其他模块并调用此函数列表仍在增长,我无法在函数调用之前/之后清除/重置returnValue。每次从外部模块创建对象时,我都需要更改作为列表的returnValue,即当第一次调用这个函数。所以我需要递归返回值是一个问题。
由于已经定义了 api,我只能更改其中的代码。
请帮忙。 谢谢。
【问题讨论】:
-
通常你不想为这类事情使用全局变量。尝试在递归链中向上或向下传递值。
-
另外,我不确定我是否正确理解了代码,你能准确解释一下你希望你的代码给出什么输出吗?您只想要找到的第一个结果还是所有结果?
-
我想将 json 和 key 作为输入,并为该特定 key 提供 json 值对。有效的 json 可以有 dict 和 list。
-
但是只有一个结果,对吧,而不是多个具有相同键的值?
-
所有这些,如果有多个键(在嵌套 json 的情况下)在这种情况下,一个列表可能是包含该键所有值的响应。