-1

I've got a nested json and I would like to find a substring in any pair's value. The results should be the pair's name or None or similar if not found at all. So for example let's assume that I am looking for the substring "met". Then for:

{
  "a": "example",
  {
     "b": "another example",
     "c": "something else"
  }
}

result should be "c" (as "met" is found in "something else") and for:

{
 "a": "example",
 {
    "b": "another example",
    "c": "yet another one"
 }
}

the result should be None as no met is found.

I have no additional information about json.

How to do it in the most efficient way?

Malvinka
  • 1,185
  • 1
  • 15
  • 36

1 Answers1

0

You could write a recursive function to check each of the values and return the key for the first match

def find_nested(item, d):
    for key, value in d.items():
        if isinstance(value, dict):
            return find_nested(item, value)
        if item in value:
            return key

For example

>>> d = {
  "a": "example",
  "d": {
     "b": "another example",
     "c": "something else"
  }
}
>>> find_nested('met', d)
'c'

>>> d = {
  "a": "example",
  "d": {
     "b": "another example",
     "c": "yet another one"
  }
}
>>> find_nested('met', d)  # returns None
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218