Toby Lockyer
Toby Lockyer

Reputation: 21

How to for loop and replace an array of values inside a key?

I have a json file (an ansible fact file)

What I'm trying to do is based on an array of keys, if the key is in the file, replace the value... This is so we can replace values people don't want to be made public (IP Address for example).

So far, the python I have can do it if its a simple Key value.... but not if its nested...

So this would be OK and it will replace...

"ansible_diff_mode": false,
"ansible_distribution": "CentOS",
"ansible_distribution_file_parsed": true,
"ansible_distribution_file_path": "/etc/redhat-release",
"ansible_distribution_file_variety": "RedHat",
"ansible_distribution_major_version": "7",
"ansible_distribution_release": "Core",

However, It can't find these values...

"ansible_all_ipv4_addresses": [
      "1.2.3.4"
  ],
 "ansible_apparmor": {
      "status": "disabled"
  },

Here is the code I'm using, and appreciate any pointers...

import json

keys_to_sanitise = ['ansible_all_ipv4_addressess','ansible_machine','ansible_bios_version',
                    'ansible_domain','environment']
factfile = 'host.yaml'

def sanitiseDict(d):
    for k in keys_to_sanitise:
        if k in d.keys():
            d.update({k: 'EXCLUDED'})
    for v in d.values():
        if isinstance(v, dict):
            sanitiseDict(v)
    return

with open(factfile, "r") as infile:
    jdata = json.load(infile)
    mydict = {}
    sanitiseDict(jdata)
    print(json.dumps(jdata))

Upvotes: 0

Views: 159

Answers (1)

Dash
Dash

Reputation: 1299

Well, for starters you have an extra s in 'ansible_all_ipv4_addressess'.

You can also clean up the syntax of sanitiseDict a bit, to get this, which reads a litte better:

def sanitiseDict(d):
    for k in keys_to_sanitise:
        if k in d:
            d[k] = 'EXCLUDED'
    for v in d.values():
        if isinstance(v, dict):
            sanitiseDict(v)

Upvotes: 1

Related Questions