如何在Ansible的json_query中移除结果的外层方括号?
The double brackets in your result happen because servers.server_details[*] returns an array (even though your server_details only has one item), and each entry in that array extracts the nested nic1-mac1_nic2-mac1 array—resulting in an array of arrays. Here are two straightforward fixes to get your desired single-level array:
Fix 1: Target the exact index (for single entry in server_details)
Since your server_details array contains just one object, you can directly access it with index [0] instead of using the wildcard [*]. Also, note that keys with hyphens need to be wrapped in quotes for json_query to parse them correctly:
mac_group_list: "{{ config_params | json_query('servers.server_details[0].nic_macaddress.\"nic1-mac1_nic2-mac1\"') }}"
Fix 2: Flatten nested arrays (works for multiple server_details entries)
If you ever have multiple objects in server_details and want to combine all their nic1-mac1_nic2-mac1 entries into a single array, add [] at the end of your query to expand nested arrays:
mac_group_list: "{{ config_params | json_query('servers.server_details[*].nic_macaddress.\"nic1-mac1_nic2-mac1\"[]') }}"
Both approaches will return your desired output:
[ "b8:83:03:81:4b:20", "b8:83:03:84:d5:1c" ]
内容的提问来源于stack exchange,提问作者Bharat Gupta

