Feature 11053: Support of jsonpath expressions in kubectl format 47/14747/3
authorgarciadeblas <gerardo.garciadeblas@telefonica.com>
Tue, 19 Nov 2024 10:23:28 +0000 (11:23 +0100)
committergarciadeblas <gerardo.garciadeblas@telefonica.com>
Mon, 25 Nov 2024 09:54:13 +0000 (10:54 +0100)
Change-Id: I68dd66320a11ed03028e12cc0266a248fc7e85a1
Signed-off-by: garciadeblas <gerardo.garciadeblas@telefonica.com>
osmclient/common/print_output.py

index 9f1e011..145c63e 100644 (file)
@@ -53,6 +53,22 @@ literal_option = click.option(
 )
 
 
+def normalize_jsonpath(json_path_expression):
+    """
+    Normalizes JSONPath expressions from kubectl format to jsonpath_ng format.
+    Example:
+    - '{.name}' becomes 'name'
+    - '{.items[0].metadata.name}' becomes 'items[0].metadata.name'
+    """
+    # Remove braces at the beginning and end
+    if json_path_expression.startswith("{") and json_path_expression.endswith("}"):
+        json_path_expression = json_path_expression[1:-1]
+    # Remove the leading '.'
+    if json_path_expression.startswith("."):
+        json_path_expression = json_path_expression[1:]
+    return json_path_expression
+
+
 def print_output(format="table", headers=["field", "value"], rows=None, data=None):
     """
     Prints content in specified format.
@@ -96,7 +112,14 @@ def print_output(format="table", headers=["field", "value"], rows=None, data=Non
         elif format.startswith("jsonpath="):
             # JSONPath expression
             json_path_expression = format.partition("=")[-1]
-            logger.debug(f"Jsonpath expression: {json_path_expression}")
+            logger.debug(f"Received jsonpath expression: {json_path_expression}")
+            # Support kubectl format
+            if json_path_expression.startswith("{") and json_path_expression.endswith(
+                "}"
+            ):
+                logger.debug("Detected kubectl JSONPath format")
+                json_path_expression = normalize_jsonpath(json_path_expression)
+            logger.debug(f"Final jsonpath expression: {json_path_expression}")
             json_path = parse(json_path_expression)
             # Apply JSONPath expression on the JSON object
             results = [match.value for match in json_path.find(data)]