简体   繁体   中英

How to search for all occurences of a key in a deeply nested json file?

I want to be able to find all occurrences of a particular json object in a json file using one of the keys that it has. For instance if I have the following json block :

{
                  "FNMIP": 1,
                  "FNMIT": 0,
                  "FNMP": {
                    "DP": {
                      "DT": 0,
                      "UF": true,
                      "DF": "yyyyMMdd"
                    },
                    "FP": {
                      "FE": null
                    }
                  },
                  "IE": true,
                  "$": "PMF"
                }

I want to search for all the json block that contain this key and then apply some kind a logic to replace it with another json object. I am not able to figure out as to how to do that stuff in Python as I am new to Python.

If I understand correctly you want to recursively walk nested dict s and for any value that matches a particular value replace it with something else. so do this:

def recursive_replace(data,match,repl):
    for k,v in data.items():
        if v == match:
            data[k] = repl #replace the matched value
        elif isinstance(v,dict):
            recursive_replace(v,match,repl)

then you can just convert the data back into json.

to instead test if "$" key is present in the data you can use the in operator:

def recursive_replace(data,repl):
    for k,v in data.items():
        if not isinstance(v,dict):
            continue
        elif "$" in v:
            data[k] = repl
        else:
            recursive_replace(v,repl)

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