Ansible使用json_query处理混合结构字段返回null的问题如何解决
核心原因
country.city.county字段类型不统一:county-a对应的取值为数组类型,county-b对应的取值为对象类型。之前的两种写法分别只能匹配其中一种类型,所以匹配不到的场景返回null。
- 带
[]的数组投影语法仅能匹配数组类型的county,遇到对象类型会返回null - 直接访问属性的语法仅能匹配对象类型的
county,遇到数组类型会返回null
适配方案
使用JMESPath内置的typeof函数做类型分支判断,单条json_query语句写法如下:
- name: 兼容不同类型county字段取值 debug: msg: "{{ msg | json_query(query) }}" vars: query: >- [].{ county: countyname, zipcode: (typeof(country.city.county) == 'array' && country.city.county[].zipcode) || country.city.county.zipcode, address: (typeof(country.city.county) == 'array' && country.city.county[].address) || country.city.county.address }
如果需要完全匹配你给出的预期输出(数组类型对应名称键为county,对象类型对应名称键为Name),可调整query为:
query: >- [].{ county: typeof(country.city.county) == 'array' && countyname, Name: typeof(country.city.county) != 'array' && countyname, zipcode: (typeof(country.city.county) == 'array' && country.city.county[].zipcode) || country.city.county.zipcode, address: (typeof(country.city.county) == 'array' && country.city.county[].address) || country.city.county.address }
若不需要区分名称键,两个条目统一使用county作为键,第一种写法即可得到符合数据逻辑的输出。
内容的提问来源于stack exchange,提问作者nauto
相关产品推荐
相关产品推荐

