From d8ece13fc2c7f6d649e4f0e9689006f1d02a54b2 Mon Sep 17 00:00:00 2001 From: "Eduardo Ramos Testillano (ert)" Date: Tue, 27 Jul 2021 02:46:25 +0200 Subject: [PATCH] Improve xml2json utility --- .../helpers/diameterJsonHelper/xml2json.py | 37 +++++++++++++++++-- 1 file changed, 33 insertions(+), 4 deletions(-) diff --git a/example/diameter/launcher/resources/rest_api/helpers/diameterJsonHelper/xml2json.py b/example/diameter/launcher/resources/rest_api/helpers/diameterJsonHelper/xml2json.py index 00c6326..707053d 100755 --- a/example/diameter/launcher/resources/rest_api/helpers/diameterJsonHelper/xml2json.py +++ b/example/diameter/launcher/resources/rest_api/helpers/diameterJsonHelper/xml2json.py @@ -1,4 +1,16 @@ #!/usr/bin/python3 +# +# Converts Anna-Diameter XML files to JSON format. +# Useful to build json content for ADML REST API: +# * Services: +# python3 xml2json.py services.xml servicesJson +# +# * Diameter messages: +# python3 xml2json.py CCR.xml diameterJson +# +# * Just xml to json: +# python3 xml2json.py file.xml + import xmltodict import json import sys @@ -6,7 +18,15 @@ import sys try: file = sys.argv[1] except: - print("Usage: " + sys.argv[0] + " ") + print("Usage: " + sys.argv[0] + " [parent name (i.e.: servicesJson, diameterJson), none by default]\n") + print(" Converts Anna-Diameter XML files to JSON format.") + print(" Useful to build json content for ADML REST API:\n") + print(" - Services:") + print(" python3 xml2json.py services.xml servicesJson\n") + print(" - Diameter messages:") + print(" python3 xml2json.py CCR.xml diameterJson\n") + print(" - Direct xml into json format:") + print(" python3 xml2json.py file.xml") sys.exit(1) try: @@ -16,10 +36,19 @@ except: print("ERROR reading '" + file + "'") sys.exit(1) +parent = None +try: + parent = sys.argv[2] +except: + pass + # although default attribute prefix is '@', anyway we will # force the value just in case xmltodict implementation # changes. The anna::core::functions::json2xml helper, # assumes this prefix in order to work properly. -my_dict=xmltodict.parse(xml, attr_prefix='@') -json_data=json.dumps(my_dict, indent=3, sort_keys=True) -print(json_data) +result=xmltodict.parse(xml, attr_prefix='@') + +if parent: + result = { parent: result } + +print (json.dumps(result, indent=3, sort_keys=True)) -- 2.20.1