Skip to content

Instantly share code, notes, and snippets.

@KPB3rd
Last active October 6, 2021 20:43
Show Gist options
  • Select an option

  • Save KPB3rd/edc2933ac4c26f5c494644f49e4d804b to your computer and use it in GitHub Desktop.

Select an option

Save KPB3rd/edc2933ac4c26f5c494644f49e4d804b to your computer and use it in GitHub Desktop.
Function to update a node in a json or xml file
import xml.etree.ElementTree as ET
import json
def nested_json_set(dic, keys, value):
for key in keys[:-1]:
dic = dic.setdefault(key, {})
dic[keys[-1]] = value
def ReplaceStringInFile(filename, child_tree, dest_ip):
# try:
if '.cfg' in filename:
# Update the json
try:
contents = json.load(open(filename))
nested_json_set(contents, child_tree, dest_ip)
except:
print('Failed to configure', filename)
# Update the file
out = open(filename, "w")
json.dump(contents, out, indent=4)
out.close()
elif '.xml' in filename:
xml_tree = ET.parse(filename)
curr_node = xml_tree
for element in child_tree[1:]: # start with the 2nd element since xml loads the top node already
curr_node = curr_node.find(element)
curr_node.text = dest_ip
xml_tree.write(filename, encoding='UTF-8', xml_declaration=True)
else:
print('Invalid filename: ', filename)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment