Untitled

mail@pastecode.io avatar
unknown
python
3 years ago
1.8 kB
6
Indexable
Never
###extracted from  https://github.com/russellballestrini/nested-lookup/blob/master/nested_lookup/lookup_api.py
from faker import Faker
from six import iteritems
fake = Faker()
import copy
import json


def nested_update(document, key, value, in_place=False, treat_as_element=True):
    if not treat_as_element and not isinstance(value, list):
        raise Exception(
            "The value must be a list when treat_as_element is False."
        )
    elif treat_as_element:
        value = [value]

    if not in_place:
        document = copy.deepcopy(document)
    return _nested_update(document=document, key=key, value=value)


def _nested_update(document, key, value):
    if isinstance(document, list):
        for list_items in document:
            _nested_update(
                document=list_items, key=key, value=value
            )
    elif isinstance(document, dict):
        for dict_key, dict_value in iteritems(document):
            if dict_key == key:
                document[key] = value[0]
                if len(value) > 1:
                    value.pop(0)
            _nested_update(
                document=dict_value, key=key, value=value
            )
    return document


my_document = {"customer_details":{"friends":[{"first_name":"Leonard","last_name":"Cohen"},{"first_name":"Iggy","last_name":"Pop"}],"first_name":"Jimi","last_name":"Hendrix"},"destination_addresses":["Philadelphia, PA, USA"],"origin_addresses":["New York, NY, USA"],"rows":[{"elements":[{"distance":{"text":"94.6 mi","value":152193},"duration":{"text":"1 hour 44 mins","value":6227},"status":"OK"}]}],"status":"OK"}

result = nested_update(my_document, key='first_name', value= fake.first_name())
print(json.dumps(result))