1

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

For instance, to check that the value is:

  • int - isinstance(value, int)
  • String - isinstance(value, str)
  • Array - isinstance(value, list)

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}
  ]
}
Christopher Peisert
  • 21,862
  • 3
  • 86
  • 117
MR Sample
  • 25
  • 6

2 Answers2

1

If JSON data schema validation is what you are after, the examples you gave can be easily handled by GoodJSON

Is list (of specific type of values)

from goodjson.validators import gj_all, foreach, is_list, is_string

validate_fn = gj_all(
    is_list(),
    foreach(is_string)
)
validate_fn(['a', 'b', 'c'])

Is dict

from goodjson.validators import foreach_key, is_dict

validate_fn = foreach_key(test=[is_dict])
validate_fn({
    'test': {
        'is_dict': 'yes'
    }
})

Is list of dict

from goodjson.validators import foreach_key, foreach, is_dict, is_list

validate_fn = foreach_key(
    test=[
        is_list(),
        foreach(is_dict)
    ]
)
validate_fn({
    'test': [{'foo': 'bar'}]
})
Namoshizun
  • 51
  • 1
  • 2
0

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

Christopher Peisert
  • 21,862
  • 3
  • 86
  • 117