简体   繁体   中英

Renaming numeric keys in nested json using python

I am trying to rename keys of json data such that if key has only numbers in it then it should get left padded with a constant string.

input_json = {'key1': {'2': 'value2', 'key3': {'key4': 'value4', '5': 'value5'}}}

output_json = {'key1': {'key2': 'value2', 'key3': {'key4': 'value4', 'key5': 'value5'}}}

This is what i was trying but did not work:

def format_json_keys(d):
    new = {}
    for k, v in d.items():
        if isinstance(v, dict):
            if k.isdecimal():
                d["key" + str(k)] = v
            format_json_keys(v)
        if isinstance(v, list):
            [format_json_keys(row) for row in v]
    return new
print(format_json_keys(input_json))

Is there a better way to achieve this?

You're not putting the updated elements in new , you're modifying the original dict. And you should replace the key regardless of the type of the value. The value type just governs how we recurse.

def format_json_keys(d):
    new = {}
    for k, v in d.items():
        newkey = "key" + str(k) if k.isdecimal() else k
        if isinstance(v, dict):
            new[newkey] = format_json_keys(v)
        elif isinstance(v, list):
            new[newkey] = [format_json_keys(row) for row in v]
        else:
            new[newkey] = v
    return new

please try this?

    def solve ( d ) :
        for k,v  in d.items() :
            if k.isdecimal ( ) :
                d["key" + k ] = v 
                d .pop ( k ) 
                
            if type (v ) == dict :
                solve ( v )
                break 
        return d

The fact that you unconditionally call the items method of the input object means that the input object has to be a dict, and that the function accepts a list only if it is a value of the given dict at the first level.

You can make the function more generic by using an if statement to determine the data type of the input object first before proceeding with the different recursive logics:

def format_json_keys(d):
    if isinstance(d, dict):
        return {'key' + k if k.isdecimal() else k: format_json_keys(v) for k, v in d.items()}
    elif isinstance(d, list):
        return list(map(format_json_keys, d))
    return d

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