如何使用JMESPath查询过滤并移除JSON中的null值?
使用JMESPath过滤并移除JSON中的Null值
针对你提供的JSON数据,你可以用以下JMESPath表达式过滤掉所有值为null的键值对:
[*].{ key: key, Students_Info: Students_Info, Adress_Info: Adress_Info | to_entries() | [?value != null] | from_entries() }
表达式拆解:
[*]:遍历数组中的每一个对象.{key: key, Students_Info: Students_Info, ...}:重新构造每个对象,保留需要的顶级键Adress_Info | to_entries():把Adress_Info对象转换成键值对数组(比如[{"key":"position","value":1},{"key":"city","value":null}])[?value != null]:过滤掉数组中value为null的项from_entries():把过滤后的键值对数组重新转换为对象
执行结果:
运行上述表达式后,会得到如下结果:
[ { "key": 111, "Students_Info": [{"recordId": 111}], "Adress_Info": {"position": 1} }, { "key": 222, "Students_Info": [{"recordId": 222}], "Adress_Info": {"position": 2, "city": "Delhi"} } ]
如果需要更通用的递归处理(移除所有层级的null值),可以使用自定义递归函数:
def remove_nulls(x) { if (type(x) == 'object') { x | to_entries() | [?value != null] | map(&{key: key, value: remove_nulls(value)}) | from_entries() } elif (type(x) == 'array') { x | map(&remove_nulls(@)) } else { x } } remove_nulls(@)
这个函数会自动处理所有嵌套的对象和数组,彻底移除所有值为null的键值对。
内容的提问来源于stack exchange,提问作者coder
相关产品推荐
相关产品推荐

