JQ数组映射:修改指定属性且保留其他属性的问题求助
JQ 1.6处理JSON数组:缺失字段赋值null并保留对象
原始JSON输入
[ { "propertyA": 11, "nestedPropertyB": [ 12 ] }, { "propertyA": 21 } ]
期望输出结果
[ { "propertyA": 11, "propertyB": 12 }, { "propertyA": 21, "propertyB": null } ]
问题重现
直接用数组流遍历,遇到无
nestedPropertyB的对象时抛出错误:jq "map({propertyB: .nestedPropertyB[]} + . | del(.nestedPropertyB))"错误信息:
jq: error (at <stdin>:10): Cannot iterate over null (null)使用可空数组流
[]?后,缺失字段的对象被直接丢弃,结果只保留第一个对象:jq "map({propertyB: .nestedPropertyB[]?} + . | del(.nestedPropertyB))"错误结果:
[ { "propertyB": 12, "propertyA": 11 } ]
解决办法
核心思路是:不管nestedPropertyB是否存在,都为propertyB赋值——存在则取数组第一个元素,不存在则赋值null,同时保留所有原对象。
方法一:使用first结合//运算符
jq 'map({propertyB: (.nestedPropertyB | first // null)} + . | del(.nestedPropertyB))'
- 说明:
.nestedPropertyB | first提取数组的第一个元素;// null表示如果前面的值为null或不存在,就用null替代,确保每个对象都能生成propertyB字段。
方法二:使用try/catch捕获异常
jq 'map({propertyB: try .nestedPropertyB[] catch null} + . | del(.nestedPropertyB))'
- 说明:
try .nestedPropertyB[]尝试遍历数组,失败(比如字段不存在)则触发catch null,赋值null。
两种方法都能得到符合预期的输出,推荐第一种更直观的写法。
内容的提问来源于stack exchange,提问作者Goddy
相关产品推荐
相关产品推荐

