简体   繁体   中英

How to return a partial JSON response using python?

I have a json (or a python dictionary) and I would like to define a whitelist of fields.

{
    "firstname": "user",
    "last_name":"test",
    "roles": ["admin", "country"], 
    "languages":{"first":"english", "second":"french"}
}

Specifying firstname, roles languages and first should output:

{
    "firstname": "user",
    "roles": ["admin", "country"],
    "languages":{"first":"english"}
}

its easy to do for first level, but how can I do it for second, third level etc...

Maybe you can make a recursive function that checks the type of each dictionary element and their white list membership. If type of element N is a dictionary, call again to function incrementing some level counter.

If you know how to do it for "first level", apply recursion to do it for "second, third, level, etc".

def dict_filter(d, keep):
    if isinstance(d, dict):
        return { k:dict_filter(v, keep) for k,v in d.iteritems() if k in keep }
    return d


orig = {
    "firstname": "user",
    "last_name":"test",
    "roles": ["admin", "country"],
    "languages":{"first":"english", "second":"french"}
}

keepers = ['firstname', 'roles', 'languages', 'first']
print dict_filter(orig, keepers)

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