I have a namespace and I want to convert the whole namespace to a dict object without concerning with the actual member names. Here’s what I’m doing now:
{% set ns=namespace(x=5,y=10,z=15) %}
...
{# do thing to accumulate values in the namespace members, say inside a for loop #}
{% set ns.x = ns.x + ... %}
...
{{ ns }} {# yields the string "<Namespace {'x': 5, 'y': 10, 'z': 15}>" #}
{% set d = ((ns|string)[11:][:-1]) | replace("'", "\"") | from_json %}
{{ d }} {# yields dict object having x,y,z }#
{{ d.x }} {# yields 5 #}
so that formula strips the text down and converts to json and then parses that to dict object.
Is there maybe a simpler way, e.g. without going through text and parsing json?
(I’ve tried dict(ns) and ns | dict to no avail.)
Thanks in advance!
Sometimes I add new members to the namespace (sometimes needed sometimes just for debugging). When I convert the namespace to a dictionary (as per my above), I can return that dictionary from a script, without some construct that mentions each member by name. (e.g. without doing {{ { 'x': ns.x, 'y': ns.y, 'z': ns.z } }}, which would seems silly if we could simply iterate on the namespace or convert directly to dict.)