[Python] Python recursive dict code is dropping key, values where the value is None

Discussão em 'Python' iniciado por Stack, Janeiro 29, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to loop over all elements in a json file. I load into a python dict object and then I am "walking" over it with recursion. The issue is when I have a chunks like this:

    {
    "layerId": "xxxx",
    "url": "https://xxxx.com/server/rest/services/General/Boundaries/MapServer/2",
    "name": "Grid",
    "placeholder": "",
    "searchFields": [
    "GRID"
    ],
    "displayField": "GRID",
    "exactMatch": false,
    "searchInCurrentMapExtent": false,
    "panToScale": false,
    "zoomScale": null,
    "maxSuggestions": 6,
    "maxResults": 6,
    "type": "query"
    }


    The code is dropping the '"zoomScale": null' key-value in the output.

    def update_json(data, url_target, item_type, source_id=None, target_id=None):
    def recursive_update(data):
    if isinstance(data, dict):
    return {k: recursive_update(v) for k, v in data.items()}
    elif isinstance(data, list):
    return [recursive_update(x) for x in data]
    elif isinstance(data, str):
    temp = data.replace('xxxx.com', url_target)
    if item_type == 'app':
    temp = temp.replace(source_id, target_id)
    return temp
    elif data is None:
    return None
    else:
    return data
    return recursive_update(data)


    If I change the return value to something other than None when data is None, e.g. 'test_null' then the key-value, 'zoomScale":"test_null"', is retained. Why is it dropping the key-value when the value is None and how can I keep the key-value in the dictionary?

    Continue reading...

Compartilhe esta Página