On Fri, 6 Nov 2020 10:59:29 -0800 (PST)
flowerysong <
ezek...@umich.edu> wrote:
> json_query() is almost never needed, ...
FWIW, Let me add to this statement:
"json_query() is almost never needed when the data is stored in
lists. json_query() is essential when the data is stored in nested
dictionaries."
Sometimes the result of using the nested dictionaries is a cleaner
code. Then json_query() is essential to help with searching. In other
words, without json_query() it might be a trade-off between a clean
code and optimal structure. See the examples below.
------------------------------------------------------------------
1) Trivial. The task below gives "msg: [A, D, G]"
- debug:
msg: "{{ data|map(attribute='a1')|list|
to_yaml }}"
vars:
data:
- {a1: A, a2: B, a3: C}
- {a1: D, a2: E, a3: F}
- {a1: G, a2: H, a3: I}
2) Feasible. First level nested dictionaries can be solved by
dict2items. The task below gives the same result "msg: [A, D, G]"
- debug:
msg: "{{ data|dict2items|
map(attribute='value')|
map(attribute='a1')|list|
to_yaml }}"
vars:
data:
dic1: {a1: A, a2: B, a3: C}
dic2: {a1: D, a2: E, a3: F}
dic3: {a1: G, a2: H, a3: I}
3) Problem. The task is more complicated when the data is stored in
nested dictionaries. For example the task below
- debug:
msg: "{{ data|dict2items|
map(attribute='value')|list|
to_yaml }}"
vars:
data:
section1:
dic1: {a1: A, a2: B, a3: C}
dic2: {a1: D, a2: E, a3: F}
section2:
dic3: {a1: G, a2: H, a3: I}
gives the list of dictionaries. It's both tricky and error-prone to
proceed in the pipe.
msg:
- dic1: {a1: A, a2: B, a3: C}
dic2: {a1: D, a2: E, a3: F}
- dic3: {a1: G, a2: H, a3: I}
4) Solution. Using json_query() to process the same data is trivial.
The task below gives the same result "msg: [A, D, G]"
- debug:
msg: "{{ data|json_query('*.*.a1')|flatten|
to_yaml }}"
vars:
data:
section1:
dic1: {a1: A, a2: B, a3: C}
dic2: {a1: D, a2: E, a3: F}
section2:
dic3: {a1: G, a2: H, a3: I}
5) Dilemma. json_query() is not needed if the same data is stored in
the lists. The task below gives the same result "msg: [A, D, G]".
Is this structure optimal for the case? Isn't nested dictionaries
a better structure? If yes, put the data into the nested
dictionaries and use json_query().
- debug:
msg: "{{ data|
map(attribute='list')|flatten|
map(attribute='a1')|list|
to_yaml }}"
vars:
data:
- section: section1
list:
- {a1: A, a2: B, a3: C}
- {a1: D, a2: E, a3: F}
- section: section2
list:
- {a1: G, a2: H, a3: I}
--
Vladimir Botka