关于使我的 JSON 查找所有嵌套实例方法更干净的建议



我正在解析未知的嵌套json对象,我事先不知道结构和深度。 我正在尝试搜索它以找到一个值。 这就是我想出的,但我发现它很模糊。 谁能告诉我如何让它看起来更pythonic,更干净?

def find(d, key):
if isinstance(d, dict):
for k, v in d.iteritems():
try:
if key in str(v):
return 'found'
except:
continue
if isinstance(v, dict):
for key,value in v.iteritems():
try:
if key in str(value):
return "found"
except:
continue
if isinstance(v, dict):
find(v)
elif isinstance(v, list):
for x in v:
find(x)
if isinstance(d, list):
for x in d:
try:
if key in x:
return "found"
except:
continue
if isinstance(v, dict):
find(v)
elif isinstance(v, list):
for x in v:
find(x)
else:
if key in str(d):
return "found"
else:
return "Not Found"

使用鸭子类型通常更"Pythonic";即,只是尝试搜索你的目标而不是使用isinstance。请参阅 type() 和 isinstance() 之间有什么区别?

但是,由于需要递归,因此有必要递归字典的值和列表的元素。(你还想搜索字典的键吗?

in运算符可用于字符串、列表和字典,因此在测试成员资格时无需将字典与列表分开。假设您不想将目标作为子字符串进行测试,请根据上一个链接使用isinstance(basestring)。若要测试目标是否在字典的值中,请测试your_dictionary.values()中的成员身份。请参阅按字典中的值获取键

因为字典值可能是列表或字典,我仍然可能会像你一样测试字典和列表类型,但我提到你可以用一个语句同时涵盖列表元素和字典键,因为你问的是 Pythonic,并且在两种类型中使用像in这样的重载运算符是 Python 的典型特征。

你使用递归的想法是必要的,但我不会用名称find定义函数,因为这是一个内置的 Python,你会(有点)影子并使递归调用的可读性降低,因为另一个程序员可能会错误地认为你正在调用内置的(作为好的做法,你可能希望保留对内置的通常访问权限,以防你想调用它。

若要测试数值类型,请使用"数字"。数字",如如何检查我的 python 对象是否为数字中所述?

此外,还有一个解决方案可以解决您的问题的变化 https://gist.github.com/douglasmiranda/5127251 .我在发布之前发现了这一点,因为 ColdSpeed 在评论中的正则表达式建议让我怀疑我是否将您引向了错误的道路。

所以像

import numbers 
def recursively_search(object_from_json, target):
if isinstance(object_from_json, (basestring, numbers.Number)):
return object_from_json==target # the recursion base cases
elif isinstance(object_from_json, list):
for element in list:
if recursively_search(element, target):
return True # quit at first match
elif isinstance(object_from_json, dict):
if target in object_from_json:
return True # among the keys
else:
for value in object_from_json.values():
if recursively_search(value, target):
return True # quit upon finding first match
else:
print ("recursively_search() did not anticipate type ",type(object_from_json))
return False
return False # no match found among the list elements, dict keys, nor dict values

最新更新