Enable print_output common function to print json and yaml from python dict or list 42/14442/2 master
authorgarciadeblas <gerardo.garciadeblas@telefonica.com>
Wed, 19 Jun 2024 16:29:50 +0000 (18:29 +0200)
committergarciadeblas <gerardo.garciadeblas@telefonica.com>
Mon, 24 Jun 2024 13:36:17 +0000 (15:36 +0200)
Change-Id: Iaab535c2e9e6361fbb2cf629031323ebd5c5293e
Signed-off-by: garciadeblas <gerardo.garciadeblas@telefonica.com>
osmclient/common/print_output.py

index a9364c8..3d72205 100644 (file)
@@ -53,7 +53,16 @@ literal_option = click.option(
 )
 
 
-def print_output(format, headers, rows):
+def print_output(format="table", headers=["field", "value"], rows=[], data=None):
+    """
+    Prints content in specified format.
+    :param format: output format (table, yaml, json, csv, jsonpath=...). Default:
+    :param headers: headers of the content
+    :param rows: rows of the content
+    :param data: dictionary or list with the content to be printed. Only applies to yaml, json or jsonpath format.
+                 If specified, headers and rows are ignored, and json/yaml/jsonpath output is generated directly from data.
+    """
+
     logger.debug("")
     if format == "table":
         table = PrettyTable(headers)
@@ -67,12 +76,13 @@ def print_output(format, headers, rows):
             table.add_row(row)
         print(table.get_csv_string())
     elif format == "json" or format == "yaml" or format.startswith("jsonpath="):
-        data = []
-        for row in rows:
-            item = {}
-            for i in range(len(row)):
-                item[headers[i]] = row[i]
-            data.append(item)
+        if not data:
+            data = []
+            for row in rows:
+                item = {}
+                for i in range(len(row)):
+                    item[headers[i]] = row[i]
+                data.append(item)
         if format == "json":
             print(json.dumps(data, indent=4))
         elif format == "yaml":