Search code examples
pythonjsonparsingreplacecharacter

how to replace character from keys in a nested json in python


"127.0.0.1": {
        "nmaprun": {
            "@scanner": "nmap",
            "@args": "nmap -v -sS -sV -sC -A -O -oX nmap 127.0.0.1 1-1024",
            "@start": "1645467733",
            "@startstr": "Mon Feb 21 23:52:13 2022",
            "@version": "7.91",
            "@xmloutputversion": "1.05",
            "scaninfo": {
                "@type": "syn",
                "@protocol": "tcp",
                "@numservices": "1000",
                "@services": "1,3-4,6-7,9,13,17,19-26,
            },
            "verbose": {
                "@level": "1"
            },
            "debugging": {
                "@level": "0"
            },
        
            "runstats": {
                "finished": {
                    "@time": "1645467744",
                    "@timestr": "Mon Feb 21 23:52:24 2022",
                    "@summary": "Nmap done at Mon Feb 21 23:52:24 2022; 1 IP address (1 host up) scanned in 12.14 seconds",
                    "@elapsed": "12.14",
                    "@exit": "success"
                }
            }
        }
    }
}

I have this scan output from Nmap. I want to parse the entire JSON and replace the '@' character with ''. how can I do this in python?


Solution

  • dic = {"127.0.0.1": {
        "nmaprun": {
            "@scanner": "nmap",
            "@args": "nmap -v -sS -sV -sC -A -O -oX nmap 127.0.0.1 1-1024",
            "@start": "1645467733",
            "@startstr": "Mon Feb 21 23:52:13 2022",
            "@version": "7.91",
            "@xmloutputversion": "1.05",
            "scaninfo": {
                "@type": "syn",
                "@protocol": "tcp",
                "@numservices": "1000",
                "@services": "1,3-4,6-7,9,13,17,19-26",
            },
            "verbose": {
                "@level": "1"
            },
            "debugging": {
                "@level": "0"
            },
    
            "runstats": {
                "finished": {
                    "@time": "1645467744",
                    "@timestr": "Mon Feb 21 23:52:24 2022",
                    "@summary": "Nmap done at Mon Feb 21 23:52:24 2022; 1 IP address (1 host up) scanned in 12.14 seconds",
                    "@elapsed": "12.14",
                    "@exit": "success"
                }
            }
        }
    }}
    def remove_at(d):
        if isinstance(d, dict):
            return {k.lstrip('@'): remove_at(v) for k, v in d.items()}
        elif isinstance(d, list):
            return [remove_at(v) for v in d]
        else:
            return d
    
    print(remove_at(dic))