在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
相关产品推荐
相关产品推荐

