Replace value in JSON file for key which can be nested by n levels

后端 未结 1 1196
长发绾君心
长发绾君心 2020-12-31 10:28

I have JSON that looks like this:

{
\"ROLE_NAME\": {
    \"FOO\": {
        \"download_url\": \"http: //something.staging/12345/buzz.zip\"
    },
    \"BAR\"         


        
1条回答
  •  一生所求
    2020-12-31 11:20

    Using recursion

    import json   
    json_txt = """
    {
    "ROLE_NAME": {
        "FOO": {
            "download_url": "http: //something.staging/12345/buzz.zip"
        },
        "BAR": {
            "download_url": "http: //something.staging/12345/fizz.zip"
        },
        "download_url": "http: //something.staging/12345/fizzbuzz.zip",
        "db_name": "somedb",
        "db_server": "dbserver.staging.dmz",
        "plugin": {
            "server_url": "http: //lab.staging.corp/server/"
        }
    }
    }
    """
    data = json.loads(json_txt)
    
    def fixup(adict, k, v):
        for key in adict.keys():
            if key == k:
                adict[key] = v
            elif type(adict[key]) is dict:
                fixup(adict[key], k, v)
    
    import pprint
    pprint.pprint( data )
    
    fixup(data, 'download_url', 'XXX')
    
    pprint.pprint( data )
    

    Output:

    {u'ROLE_NAME': {u'BAR': {u'download_url': u'http: //something.staging/12345/fizz.zip'},
                    u'FOO': {u'download_url': u'http: //something.staging/12345/buzz.zip'},
                    u'db_name': u'somedb',
                    u'db_server': u'dbserver.staging.dmz',
                    u'download_url': u'http: //something.staging/12345/fizzbuzz.zip',
                    u'plugin': {u'server_url': u'http: //lab.staging.corp/server/'}}}
    {u'ROLE_NAME': {u'BAR': {u'download_url': 'XXX'},
                    u'FOO': {u'download_url': 'XXX'},
                    u'db_name': u'somedb',
                    u'db_server': u'dbserver.staging.dmz',
                    u'download_url': 'XXX',
                    u'plugin': {u'server_url': u'http: //lab.staging.corp/server/'}}}
    

    0 讨论(0)
提交回复
热议问题