From 77b516f6a80e845c713762dfd4aeef06a0bb8956 Mon Sep 17 00:00:00 2001 From: nicholasmhughes Date: Wed, 5 Jul 2023 11:42:20 -0400 Subject: [PATCH] adding to_entries and from_entries functions as jinja filters --- doc/topics/jinja/index.rst | 51 ++++++++++++++++++++++++++++++++++++++ salt/utils/data.py | 2 ++ 2 files changed, 53 insertions(+) diff --git a/doc/topics/jinja/index.rst b/doc/topics/jinja/index.rst index ad8e436a00a..2f68362fb96 100644 --- a/doc/topics/jinja/index.rst +++ b/doc/topics/jinja/index.rst @@ -1682,6 +1682,57 @@ Returns: .. _`JMESPath language`: https://jmespath.org/ .. _`jmespath`: https://github.com/jmespath/jmespath.py + +.. jinja_ref:: to_entries + +``to_entries`` +-------------- + +.. versionadded:: 3007.0 + +A port of the ``to_entries`` function from ``jq``. This function converts between an object and an array of key-value +pairs. If ``to_entries`` is passed an object, then for each ``k: v`` entry in the input, the output array includes +``{"key": k, "value": v}``. The ``from_entries`` function performs the opposite conversion. ``from_entries`` accepts +"key", "Key", "name", "Name", "value", and "Value" as keys. + +Example: + +.. code-block:: jinja + + {{ {"a": 1, "b": 2} | to_entries }} + +Returns: + +.. code-block:: text + + [{"key":"a", "value":1}, {"key":"b", "value":2}] + + +.. jinja_ref:: to_entries + +``from_entries`` +-------------- + +.. versionadded:: 3007.0 + +A port of the ``from_entries`` function from ``jq``. This function converts between an array of key-value pairs and an +object. If ``from_entries`` is passed an object, then the input is expected to be an array of dictionaries in the format +of ``{"key": k, "value": v}``. The output will be be key-value pairs ``k: v``. ``from_entries`` accepts "key", "Key", +"name", "Name", "value", and "Value" as keys. + +Example: + +.. code-block:: jinja + + {{ [{"key":"a", "value":1}, {"key":"b", "value":2}] | from_entries }} + +Returns: + +.. code-block:: text + + {"a": 1, "b": 2} + + .. jinja_ref:: to_snake_case ``to_snake_case`` diff --git a/salt/utils/data.py b/salt/utils/data.py index 07f4a2fed91..aded1f695c7 100644 --- a/salt/utils/data.py +++ b/salt/utils/data.py @@ -1692,6 +1692,7 @@ def shuffle(value, seed=None): return sample(value, len(value), seed=seed) +@jinja_filter("to_entries") def to_entries(data): """ Convert a dictionary or list into a list of key-value pairs (entries). @@ -1718,6 +1719,7 @@ def to_entries(data): return ret +@jinja_filter("from_entries") def from_entries(entries): """ Convert a list of key-value pairs (entries) into a dictionary.