关于清理JSON findallnestedocurrences方法的建议

2024-04-23 23:00:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在解析未知的嵌套json对象,我不知道结构和深度提前。我正在尝试搜索它以找到一个值。这是我想出来的,但我觉得很无聊。有人能告诉我怎么让这个看起来更像Python,更干净吗?在

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"

Tags: keyinforreturniffinddictlist
1条回答
网友
1楼 · 发布于 2024-04-23 23:00:15

使用duck类型通常更“python”;也就是说,只需尝试搜索目标而不是使用isinstance。见What are the differences between type() and isinstance()?

但是,由于需要递归,因此有必要递归字典和列表元素的。(是否也要搜索词典的关键字?)在

in运算符可以同时用于字符串、列表和字典,因此在测试成员身份时不需要将字典与列表分开。假设您不想将目标作为子字符串进行测试,请按照上一个链接使用isinstance(basestring)。要测试目标是否在字典的中,请测试your_dictionary.values()中的成员资格。见Get key by value in dictionary

因为dictionary值可能是list或dictionary,所以我仍然可以像您那样测试dictionary和list类型,但是我提到,您可以用一个语句同时覆盖list元素和dictionary key,因为您要问的是python,在两种类型中使用重载的oeprator,如in,这是典型的Python。在

你使用递归的想法是必要的,但是我不会用find来定义函数,因为这是一个Python内置函数,你会(某种程度上)隐藏递归调用,使递归调用的可读性变差,因为另一个程序员可能会误认为你在调用内置函数(作为一个好的实践,您可能希望保留对内置的常规访问,以防调用它。)

要测试数字类型,请使用`数字。数字'如How can I check if my python object is a number?所述

另外,在https://gist.github.com/douglasmiranda/5127251有一个问题的变体的解决方案。我发现这是因为ColdSpeed在评论中的regex建议让我怀疑我是不是在引导你走上了错误的道路。在

所以有点像

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

相关问题 更多 >