You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 20:22:14