Ansible json-query路径,按内容选择项目 [英] ansible json-query path to select item by content
问题描述
有人知道在下面的示例JSON中可以使用哪种json-query过滤器来选择Tigger的食物吗? JSON是庞大且相对复杂的AWS Blob的简化代表.
Does anyone know what json-query filter can be used to select Tigger's food in the sample JSON below? The JSON is a simplified stand-in for a massive and relatively complicated AWS blob.
一些背景:我很高兴发现Ansible有一个json-query过滤器.鉴于我正在尝试从AWS JSON Blob中选择一个元素,因此看起来这正是我所需要的.但是,我很快遇到了麻烦,因为AWS对象具有标签,并且我需要按标签选择项目.
Some background: I was rather pleased to discover that Ansible has a json-query filter. Given that I was trying to select an element from an AWS JSON blob this looked as if it was just what I needed. However I quickly ran into trouble because the AWS objects have tags and I needed to select items by tag.
我尝试了等效于Foods[Tags[(Key='For') & (Value='Tigger')]]
的选择器路径,但没有设法使其生效.使用独立的json-query库,例如 https://www.npmjs.com/package/json -query 我可以使用parent
属性,但这似乎并没有出现在Ansible中,除了与json-query的核心思想有所偏离之外.
I tried selector paths equivalent to Foods[Tags[(Key='For') & (Value='Tigger')]]
and similar but didn't manage to get it to work. Using a standalone json-query library such as https://www.npmjs.com/package/json-query I can use the parent
attribute but that does not appear to be in Ansible, quite apart from being a deviation from the core idea of json-query.
避开问题并使用jsonpath选择器可能会更好. jsonpath与json-query相似,是xpath的翻译.
It might be better to sidestep the problem and use a jsonpath selector. jsonpath is similar to json-query and is a translation from xpath.
{ "Foods" :
[ { "Id": 456
, "Tags":
[ {"Key":"For", "Value":"Heffalump"}
, {"Key":"Purpose", "Value":"Food"}
]
}
, { "Id": 678
, "Tags":
[ {"Key":"For", "Value":"Tigger"}
, {"Key":"Purpose", "Value":"Food"}
]
}
, { "Id": 911
, "Tags":
[ {"Key":"For", "Value":"Roo"}
, {"Key":"Purpose", "Value":"Food"}
]
}
]
}
参考文献
- json_query中的ansible: http://docs.ansible.com/ansible/playbooks_filters.html# json-query-filter
- json-query独立节点: https://www.npmjs.com/package/json -查询
- jmespath,库可使用: http://jmespath.org/
- json-query独立python: https://pypi.python.org/pypi/jsonquery/(鲱鱼)
- json_query in ansible: http://docs.ansible.com/ansible/playbooks_filters.html#json-query-filter
- json-query standalone node: https://www.npmjs.com/package/json-query
- jmespath, the library ansible uses: http://jmespath.org/
- json-query standalone python: https://pypi.python.org/pypi/jsonquery/ (red herring)
References
推荐答案
是否需要ID列表?如果是这样,请尝试:
Do you need list of ids? If so, try:
- debug: msg="{{ lookup('file','test.json') | from_json | json_query(query) }}"
vars:
query: "Foods[].{id: Id, for: (Tags[?Key=='For'].Value)[0]} | [?for=='Tigger'].id"
首先构造具有必要字段的简单对象,然后将其通过管道传递给过滤器.
First construct simple objects with necessary fields and then pipe it to a filter.
这篇关于Ansible json-query路径,按内容选择项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!