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

在jq中如何筛选JSON所有层级的指定属性并保留结构?

使用jq过滤JSON并保留原结构

需求回顾

原始JSON:

{"data":[ {"prop1":"a", "prop2":"b", "prop3":"c", "prop4":"d", "nestedprops":{"nestedprop1":"A","nestedprop2":"B"} }, {"prop2":"b", "prop3":"c", "nestedprops":{"nestedprop1":"A"}}, {"prop3":"c"} ]}

需要保留data顶层结构,仅保留每个数组元素的prop1、prop2以及嵌套对象中的nestedprop1,过滤其他字段。

正确的jq命令

.data |= map({prop1, prop2} + ( .nestedprops | {nestedprops: {nestedprop1}}? ))

命令说明

  • .data |= map(...):针对顶层的data数组做映射处理,同时保留整个JSON的原始结构
  • {prop1, prop2}:提取当前对象中的prop1和prop2,如果字段不存在则自动忽略,不会生成空键
  • + ( .nestedprops | {nestedprops: {nestedprop1}}? ):处理嵌套的nestedprops对象,提取其中的nestedprop1并包装为nestedprops结构;末尾的?用于容错,当原对象没有nestedprops字段时,这部分不会报错,也不会添加多余的键

执行结果

运行上述命令后,得到的结果与预期一致:

{"data":[ {"prop1":"a", "prop2":"b", "nestedprops":{"nestedprop1":"A"} }, {"prop2":"b", "nestedprops":{"nestedprop1":"A"}}, {} ]}

进阶调整(可选)

如果希望当nestedprops存在但没有nestedprop1时,不生成空的nestedprops键,可以使用以下命令:

.data |= map({prop1, prop2} + ( .nestedprops | select(has("nestedprop1")) | {nestedprops: {nestedprop1}} )? )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 06:42:18