pythonjson

How to parse JSON and determine if values are collections or nested collections?


I am looking for different ways to check values within JSON.

For instance, to check that the value is:

But what is the cleanest way to check if values are list, dict or a list of dictionaries? How to correctly differentiate between them?

Example

{
  "test": ["a","b"]
}

vs

{
  "test": {"a":0, "b":1}
}

vs

{
  "test": [
    {"a":0},
    {"b":1}
  ]
}

Solution

  • To recursively search through a JSON data structure, and handle the case where the items are collections such as lists or dictionaries, you could do something like the following.

    Example: Recursively search for JSON key

    def find_key(json_input, lookup_key):
        if isinstance(json_input, dict):
            for k, v in json_input.items():
                if k == lookup_key:
                    yield v
                else:
                    yield from find_key(v, lookup_key)
        elif isinstance(json_input, list):
            for item in json_input:
                yield from find_key(item, lookup_key)
    

    Also, be sure to take advantage of the standard library json package. The main functions for JSON encoding and decoding are:

    See also