如何按hname属性长度及斜杠数量对JQuery响应结果进行降序排序?
如何按hname属性长度及斜杠数量对JQuery响应结果进行降序排序?
看起来你是想用Ansible处理从jQuery获取到的JSON数据,按hname的斜杠数量或长度降序排序,但之前的写法出了问题。我来帮你梳理下问题和解决方案:
首先说下你之前写法的问题:你把字符串处理逻辑直接塞到了sort过滤器的attribute参数里,但attribute只能指定对象的属性名,没法直接对属性做链式的正则替换和长度计算,这才导致了那个变量未定义的错误。
接下来给你几个可行的正确写法:
1. 按hname中的斜杠数量降序排序
我们可以用sort的key参数,通过lambda表达式来动态计算每个元素的斜杠数量作为排序依据:
- name: 按hname的斜杠数量降序排序 set_fact: sorted_id_hname_type: "{{ id_hname_type | sort(key=item => item.hname | regex_findall('/') | length, reverse=true) }}"
这里用regex_findall('/')匹配所有斜杠,再取结果列表的长度,以此作为排序的key,reverse=true实现降序,刚好符合你要把层级更深(斜杠更多)的条目排在前面的需求。
2. 按hname的字符串长度降序排序
如果要按hname的总长度排序,写法类似,直接取字符串长度作为key:
- name: 按hname的长度降序排序 set_fact: sorted_id_hname_type: "{{ id_hname_type | sort(key=item => item.hname | length, reverse=true) }}"
3. 同时结合两个条件排序(斜杠数量优先,长度次之)
如果需要先按斜杠数量排序,当斜杠数量相同时再按hname长度排序,可以把两个值组成列表作为key:
- name: 先按斜杠数量、再按hname长度降序排序 set_fact: sorted_id_hname_type: "{{ id_hname_type | sort(key=item => [item.hname | regex_findall('/') | length, item.hname | length], reverse=true) }}"
兼容旧版Ansible的写法(如果你的Ansible版本低于2.10)
如果你的Ansible版本不支持lambda表达式,可以先给每个条目添加一个临时的计算属性,再按这个属性排序:
- name: 按斜杠数量降序排序(兼容旧版Ansible) set_fact: sorted_id_hname_type: "{{ id_hname_type_with_counts | sort(reverse=true, attribute='slash_count') }}" vars: id_hname_type_with_counts: "{{ id_hname_type | map('combine', {'slash_count': item.hname | regex_findall('/') | length}) | list }}"
用这些写法处理你提供的示例数据,就能得到你预期的排序结果,之后提取id列表就没问题啦。
备注:内容来源于stack exchange,提问作者afranco.pt
相关产品推荐
相关产品推荐

