I have a JSON file with some data on it, like the below one:
{
"84d0da32-c945-9844-86cc-4b4bd6100dc5": {
"UUID": "84d0da32-c945-9844-86cc-4b4bd6100dc5",
"GroupName": "TEST1",
"EntryTitle": "host1",
"Username": "sys",
"NewPassword": "@PVmkiajauauajjhfz-5/NN"
},
"test": {
"UUID": "5c3c162f-0a80-f949-85a0-afcf9aedb6c8",
"GroupName": "TEST2",
"EntryTitle": "host2",
"Username": "sys",
"NewPassword": "H7-uPz2mkaaua@ki7q?NSs?"
}
}
I am trying to filter only the field GroupName
or EntryTitle
, with json_query
but it always give null
, if I try to write all GroupName
field, it returns both.
I only want to pass for example if GroupName
is TEST2
return the EntryTitle
field.
Example of my code until now:
- name: load json data
shell: cat entries.json
register: result
- name: save json do var
set_fact:
jsondata: "{{ result.stdout | from_json }}"
- name: server name
set_fact:
servername: "{{ jsondata | json_query(jq) }}"
vars:
jq: "*.GroupName"
- name: Print
debug:
msg: "{{ item }}"
with_items:
- "{{ servername }}"
2
Answers
I can’t reproduce your problem. Your code works as expected. Given the file
read the file
and convert the result from JSON. Declare the variable
gives
The filter json_query
gives the list of the attribute GroupName values
Example of a complete playbook for testing
gives
I guess your trial at a query was something like
This does indeed returns an empty list (
[]
) as*
is an object projection, and in order to chain a projection on top of another projection, in JMESPath, you have to reset the previous projection, with a pipe expression.Here, the query
[?GroupName == `TEST2`]
is a filter projection, so you indeed have to follow the above mentioned rule by resetting the projection created by the object projection:So, you should update your
server name
task accordingly:Side notes:
shell
task. If the file is on the remote node, use theslurp
module, if the file is local to the controller, use afile
lookuploop
syntax instead of thewith_*
one, already. There are plenty of examples to migrate them in the documentation and the syntax usually feels more aligned across all different loops of your tasks, as the logic is expressed in filters rather than in the variation of thewith_*
usedSo, if the file is on the remote node(s):
Would yield
And if the file is on the controller node, then you can cut it down to a single task:
Would yield
Extra note: the
| [0]
is once again a pipe expression meant to reset the previous projection, as explained before, in order to get the element[0]
, so the first one, of the JSON array.