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

JQ生成JSON对象遇缺失键无输出问题的解决问询

解决JQ命令在缺失属性时返回NULL的需求

示例JSON文件

example1

{"label": "Example1","attributes": [{"objectTypeAttribute": {"name": "Created"},"objectAttributeValues": [{"value": "create time 1"}]},{"objectTypeAttribute": {"name": "Updated"},"objectAttributeValues": [{"value": "update time 1"}]}]}

example2

{"label": "Example2","attributes": [{"objectTypeAttribute": {"name": "Created"},"objectAttributeValues": [{"value": "create time 2"}]}]}

原命令问题

执行以下命令处理example1时能得到预期结果:

cat example1 | jq '{created: .attributes[] | select(.objectTypeAttribute.name=="Created").objectAttributeValues[0].value,updated:.attributes[] | select(.objectTypeAttribute.name=="Updated").objectAttributeValues[0].value}'

输出结果:

{"created": "create time 1","updated": "update time 1"}

但处理example2时无输出,期望得到:

{"created": "create time 2","updated": null}

解决方案

原命令的问题在于.attributes[]会遍历数组所有元素,无匹配项时直接过滤掉整个结果,且多元素场景可能产生重复输出。以下两种方式可解决问题:

方式1:用first()精准获取匹配项

通过first()锁定第一个匹配的属性对象,结合// null处理缺失场景:

jq '{
  created: (first(.attributes[] | select(.objectTypeAttribute.name == "Created")) | .objectAttributeValues[0].value) // null,
  updated: (first(.attributes[] | select(.objectTypeAttribute.name == "Updated")) | .objectAttributeValues[0].value) // null
}'

方式2:先转键值对对象再取值

先将attributes数组转换为键值对映射,再直接按属性名取值,缺失时返回null:

jq '
.attr_map = (.attributes | map({(.objectTypeAttribute.name): .objectAttributeValues[0].value}) | add) |
{
  created: .attr_map.Created // null,
  updated: .attr_map.Updated // null
} | del(.attr_map)
'

验证结果

处理example1

输出:

{"created": "create time 1", "updated": "update time 1"}

处理example2

输出:

{"created": "create time 2", "updated": null}

内容的提问来源于stack exchange,提问作者chris93

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 02:41:03