ansible json-query 路径以按内容选择项目 [英] ansible json-query path to select item by content
问题描述
有谁知道在下面的示例 JSON 中可以使用什么 json-query 过滤器来选择跳跳虎的食物?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"}
]
}
]
}
参考资料
- ansible 中的 json_query:http://docs.ansible.com/ansible/playbooks_filters.html#json查询过滤器
- json-query 独立节点:https://www.npmjs.com/package/json-查询
- jmespath,ansible 使用的库:http://jmespath.org/
- json-query 独立 python:https://pypi.python.org/pypi/jsonquery/(红鲱鱼)
推荐答案
您需要 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屋!