You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求优化嵌套JSON全匹配查找方法,使其更具Python风格

Hey there! Let's clean up that nested JSON search code to be more Pythonic—we'll use recursion, handle all common JSON types (dicts and lists), and make it concise and readable.

First, let's call out the gaps in your original code:

  • It only handles dicts, not lists (JSON arrays translate to Python lists, so this is a critical oversight)
  • Nested loops for dicts are redundant when recursion can handle arbitrary depth automatically
  • Broad try-except blocks hide errors instead of addressing them properly
  • Uses Python 2's outdated iteritems() instead of Python 3's modern values()

Here are refined, Pythonic versions tailored to different common use cases:

Option 1: Search for a substring in any value (matches your original logic)

This function checks if your target string exists as a substring in any value (converted to string) across the nested structure, and returns True immediately when found (short-circuiting for efficiency):

def find_nested(data, target):
    # Check if target is a substring in the current element's string representation
    if target in str(data):
        return True
    
    # Recurse through all values in the dict
    if isinstance(data, dict):
        return any(find_nested(value, target) for value in data.values())
    
    # Recurse through elements in lists/tuples (handles JSON arrays)
    if isinstance(data, (list, tuple)):
        return any(find_nested(item, target) for item in data)
    
    # If none of the above, target isn't found
    return False

Option 2: Exact value match (if that's your actual goal)

If you want to find an exact value match instead of a substring, adjust the first condition:

def find_nested_exact(data, target):
    if data == target:
        return True
    
    if isinstance(data, dict):
        return any(find_nested_exact(value, target) for value in data.values())
    
    if isinstance(data, (list, tuple)):
        return any(find_nested_exact(item, target) for item in data)
    
    return False

Option 3: Search for a specific key (common nested dict task)

If your goal was actually to check if a key exists anywhere in the nested structure, use this version:

def find_key_nested(data, target_key):
    if isinstance(data, dict):
        if target_key in data:
            return True
        # Recurse through all dict values to find nested keys
        return any(find_key_nested(value, target_key) for value in data.values())
    
    if isinstance(data, (list, tuple)):
        # Check each element in the list/tuple for nested keys
        return any(find_key_nested(item, target_key) for item in data)
    
    return False

Why this is more Pythonic:

  • Recursion: Naturally handles arbitrary nesting depth without manual nested loops
  • any() with generator expressions: Concise, readable, and efficient—stops searching as soon as a match is found
  • Explicit type checking: Avoids broad try-except blocks by directly checking for dicts/lists
  • Python 3 compatible: Uses modern syntax like values() instead of Python 2's iteritems()
  • Covers all JSON types: Handles both objects (dicts) and arrays (lists/tuples)

You can test these functions with sample data like this:

# Example nested JSON data
nested_data = {
    "level1": {
        "level2": "my_target_string",
        "level2_list": [1, 2, {"level3": "another_target"}]
    }
}

print(find_nested(nested_data, "target"))  # Output: True
print(find_nested_exact(nested_data, "another_target"))  # Output: True
print(find_key_nested(nested_data, "level3"))  # Output: True

内容的提问来源于stack exchange,提问作者Jacek Perry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:47:34