Yes, you can do this recursively, if all you have is lists and dictionaries, then that is pretty trivial. Test for the object type, and for containers, recurse:
def unwrap_data(obj):
if isinstance(obj, dict):
if 'data' in obj:
obj = obj['data']
return {key: unwrap_data(value) for key, value in obj.items()}
if isinstance(obj, list):
return [unwrap_data(value) for value in obj]
return obj
Personally, I like using the @functools.singledispatch()
decorator to create per-type functions to do the same work:
from functools import singledispatch
@singledispatch
def unwrap_data(obj):
return obj
@unwrap_data.register(dict)
def _handle_dict(obj):
if 'data' in obj:
obj = obj['data']
return {key: unwrap_data(value) for key, value in obj.items()}
@unwrap_data.register(list)
def _handle_list(obj):
return [unwrap_data(value) for value in obj]
This makes it a little easier to add additional types to handle later on.
Demo:
>>> request = {"data":{"a":[{"data": {"b": {"data": {"c": "d"}}}}]}}
>>> unwrap_data(request)
{'a': [{'b': {'c': 'd'}}]}
0
solved Python dictionary operations