简体   繁体   中英

How can I access nested JSON keys dynamically by using an array in Python?

What I'd like to do, is to create a function, to which I pass a string array and a json, that would check if the json has the keys specified by the array and return their corresponding value. Here I have a snippet that works for top-level keys (and their values):

import json


def check_key_and_return(json, keys):
    if keys[0] in json:
        return json[keys[0]]
    else:
        return ''


if __name__ == '__main__':
    json_s = '{"a":{"b":1}}'
    json = json.loads(json_s)
    print(check_key_and_return(json, ['a']))

this returns {'b': 1} .

I'd like to be able to pass multiple strings, like check_key_and_return(json, ['a', 'b']) , so that the function would return 1 (or an empty string if no match is found.

Thank you.

Since nested keys become value for the parent key, you would have an iterator to fetch all keys. One of the ways could be:

import numpy as np
import pandas as pd
import json
from collections.abc import Mapping
def nested_keys(d) -> set:
    """
    Return a set containing all nested keys.
    """
    # If it is not a dict-like object, return an empty set
    if not isinstance(d, Mapping):
        return set()

    keys = d.keys()
    for v in d.values():
        # Update the keys set with the keys in each value by using the union (or) operator: |
        keys |= nested_keys(v)

    return keys

str='{"a":{"b":1}}'
json_str = json.loads(str)
print(json_str)
all_keys=nested_keys(json_str)
print(nested_keys(json_str))
find_set1={'a','c'}
print(find_set1.issubset(all_keys))
find_set2={'a','b'}
print(find_set2.issubset(all_keys))

Output:

{'a': {'b': 1}}
{'a', 'b'}
False
True

Now based on the above condition(True/False) you can return 1 or empty string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM