如何在 Jinja 中过滤字典? [英] How to filter dictionaries in Jinja?
问题描述
我有一个包的字典,包名是键,一些细节的字典是值:
{php7.1-readline":{"最新": "7.1.9-1+ubuntu14.04.1+deb.sury.org+1",起源":[ppa.launchpad.net"],"版本": "7.1.6-2~ubuntu14.04.1+deb.sury.org+1","www": "http://www.php.net/"},php7.1-xml":{"最新": "7.1.9-1+ubuntu14.04.1+deb.sury.org+1",起源":[ppa.launchpad.net"],"版本": "7.1.6-2~ubuntu14.04.1+deb.sury.org+1","www": "http://www.php.net/"},普利茅斯":{版本":0.8.8-0ubuntu17.1"},....}
我想将上述内容简化为仅包含值中具有 latest
属性的包的字典.
看起来 json_query
是要使用的过滤器,但我无法弄清楚语法.那里的例子似乎都对字典进行操作,而不是对字典相同......
例如,如果我将上述字典管道"到 json_query('*.latest')
中,我会得到实际最新版本的列表:><预><代码>["7.1.9-1+ubuntu14.04.1+deb.sury.org+1","7.1.9-1+ubuntu14.04.1+deb.sury.org+1","7.1.6-2~ubuntu14.04.1+deb.sury.org+1"]
如何获取整个字典元素?
有希望吗?
With dict2items
过滤器 于 2017 年 12 月添加,可以使用本机功能:
- 调试:msg: "{{ dict(pkg | dict2items | json_query('[?value.latest].[key, value.latest]')) }}"
结果:
"msg": {"php7.1-readline": "7.1.9-1+ubuntu14.04.1+deb.sury.org+1","php7.1-xml": "7.1.9-1+ubuntu14.04.1+deb.sury.org+1"}
I have a dictionary of packages with package-name being the key and a dictionary of some details being the value:
{
"php7.1-readline": {
"latest": "7.1.9-1+ubuntu14.04.1+deb.sury.org+1",
"origins": [
"ppa.launchpad.net"
],
"version": "7.1.6-2~ubuntu14.04.1+deb.sury.org+1",
"www": "http://www.php.net/"
},
"php7.1-xml": {
"latest": "7.1.9-1+ubuntu14.04.1+deb.sury.org+1",
"origins": [
"ppa.launchpad.net"
],
"version": "7.1.6-2~ubuntu14.04.1+deb.sury.org+1",
"www": "http://www.php.net/"
},
"plymouth": {
"version": "0.8.8-0ubuntu17.1"
},
....
}
I'd like to reduce the above to a dictionary with only the packages, that have the latest
-attribute in their values.
It would seem like json_query
is the filter to use, but I can't figure out the syntax. The examples out there all seem to operate on lists of dictionaries, not dictionaries of same...
For example, if I "pipe" the above dictionary into json_query('*.latest')
, I get the list of the actual latest versions:
[
"7.1.9-1+ubuntu14.04.1+deb.sury.org+1",
"7.1.9-1+ubuntu14.04.1+deb.sury.org+1",
"7.1.6-2~ubuntu14.04.1+deb.sury.org+1"
]
How can I get the entire dictionary-elements instead?
Any hope?
With dict2items
filter added in December 2017, it is possible using native functionality:
- debug:
msg: "{{ dict(pkg | dict2items | json_query('[?value.latest].[key, value.latest]')) }}"
The result:
"msg": {
"php7.1-readline": "7.1.9-1+ubuntu14.04.1+deb.sury.org+1",
"php7.1-xml": "7.1.9-1+ubuntu14.04.1+deb.sury.org+1"
}
这篇关于如何在 Jinja 中过滤字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!