Add suite testing IoTDM plugin infrastructure
[integration/test.git] / csit / libraries / norm_json.py
index 8702b55121c6bcc2b6a6191f78acfe47d10a7378..e113e7fe656ac36c835b52554225827799f6ec9a 100644 (file)
@@ -6,6 +6,7 @@
 # and is available at http://www.eclipse.org/legal/epl-v10.html
 
 import collections as _collections
+import jmespath
 try:
     import simplejson as _json
 except ImportError:  # Python2.7 calls it json.
@@ -105,11 +106,12 @@ def loads_sorted(text, strict=False):
 
 def dumps_indented(obj, indent=1):
     """
-    Wrapper for json.dumps with default indentation level. Adds newline.
+    Wrapper for json.dumps with default indentation level.
 
     The main value is that BuiltIn.Evaluate cannot easily accept Python object
     as part of its argument.
     Also, allows to use something different from RequestsLibrary.To_Json
+
     """
     pretty_json = _json.dumps(obj, separators=(',', ': '), indent=indent)
     return pretty_json + '\n'  # to avoid diff "no newline" warning line
@@ -152,15 +154,30 @@ def sort_bits(obj, keys_with_bits=[]):
     return obj
 
 
-def normalize_json_text(text, strict=False, indent=1, keys_with_bits=[]):
+def normalize_json_text(text, strict=False, indent=1, keys_with_bits=[], jmes_path=None):
     """
     Attempt to return sorted indented JSON string.
 
+    If jmes_path is set the related subset of JSON data is returned as
+    indented JSON string if the subset exists. Empty string is returned if the
+    subset doesn't exist.
+    Empty string is returned if text is not passed.
     If parse error happens:
     If strict is true, raise the exception.
     If strict is not true, return original text with error message.
     If keys_with_bits is non-empty, run sort_bits on intermediate Python object.
     """
+
+    if not text:
+        return ""
+
+    if jmes_path:
+        json_obj = _json.loads(text)
+        subset = jmespath.search(jmes_path, json_obj)
+        if not subset:
+            return ""
+        text = _json.dumps(subset)
+
     try:
         object_decoded = loads_sorted(text)
     except ValueError as err:
@@ -170,5 +187,7 @@ def normalize_json_text(text, strict=False, indent=1, keys_with_bits=[]):
             return str(err) + '\n' + text
     if keys_with_bits:
         sort_bits(object_decoded, keys_with_bits)
+
     pretty_json = dumps_indented(object_decoded, indent=indent)
+
     return pretty_json