From 2d55a50f3ee597386edd57882bed9fb24a0dbdc5 Mon Sep 17 00:00:00 2001 From: Renuka Manavalan <47282725+renukamanavalan@users.noreply.github.com> Date: Tue, 17 Dec 2019 13:41:08 -0800 Subject: [PATCH] A generic JSON file updater, which can add/update-existing attributes. (#770) * A generic JSON file updater, which can add/update-existing attributes. This tool would be used to update /etc/sonic/core_analyzer.rc.json file to add credentials by HW proxy. * Updated per review comments. The option is better named. --- scripts/update_json.py | 55 ++++++++++++++++++++++++++++++++++++++++++ setup.py | 1 + 2 files changed, 56 insertions(+) create mode 100755 scripts/update_json.py diff --git a/scripts/update_json.py b/scripts/update_json.py new file mode 100755 index 000000000000..a42603e8fe44 --- /dev/null +++ b/scripts/update_json.py @@ -0,0 +1,55 @@ +#! /usr/bin/env python + +import os +import sys +import json +import argparse + +TMP_SUFFIX = ".tmp" +BAK_SUFFIX = ".bak" + +def dict_update(dst, patch): + for k in patch.keys(): + if type(patch[k]) == dict: + dst[k] = dict_update(dst[k], patch[k]) + else: + dst[k] = patch[k] + return dst + +def do_update(rcf, patchf): + dst = {} + patch = {} + + tmpf = rcf + TMP_SUFFIX + bakf = rcf + BAK_SUFFIX + + with open(rcf, "r") as f: + dst = json.load(f) + + with open(patchf, "r") as f: + patch = json.load(f) + + dst = dict_update(dst, patch) + + with open(tmpf, "w") as f: + json.dump(dst, f, indent = 4) + + os.rename(rcf, bakf) + os.rename(tmpf, rcf) + + +def main(): + parser = argparse.ArgumentParser(description="Update JSON based file") + parser.add_argument("-u", "--update", help="JSON file to be updated") + parser.add_argument("-p", "--patch", help="JSON file holding patch") + args = parser.parse_args() + + if not args.update or not args.patch: + raise Exception("check usage") + + do_update(args.update, args.patch) + +if __name__ == '__main__': + main() + + diff --git a/setup.py b/setup.py index 69717fb186d7..160129bc166a 100644 --- a/setup.py +++ b/setup.py @@ -90,6 +90,7 @@ 'scripts/route_check_test.sh', 'scripts/sfpshow', 'scripts/teamshow', + 'scripts/update_json.py', 'scripts/warm-reboot', 'scripts/watermarkstat', 'scripts/watermarkcfg'