如何使用jq获取JSON对象前X层深度并移除其余层级内容?
使用jq保留JSON指定层级深度的内容
要保留JSON的前X层内容并截断更深层级,可以通过自定义jq递归函数实现。以下针对你的需求(保留前3层,移除Location层级以下的内容)给出具体方案:
核心实现
定义递归函数控制深度,对对象/数组遍历后截断指定层级以外的内容:
def keep_up_to_depth($max_depth): # 达到指定深度时,用空对象/数组替换深层内容,基础类型直接保留 if $max_depth == 0 then if type == "object" then {} elif type == "array" then [] else . end else # 未达深度则递归处理子节点 if type == "object" then with_entries(.value |= keep_up_to_depth($max_depth - 1)) elif type == "array" then map(keep_up_to_depth($max_depth - 1)) else . end end; # 调用函数,保留前3层 keep_up_to_depth(3)
使用示例
假设你的JSON数据保存在data.json文件中,执行以下命令即可得到结果:
jq 'def keep_up_to_depth($max_depth): if $max_depth == 0 then (if type == "object" then {} elif type == "array" then [] else . end) else (if type == "object" then with_entries(.value |= keep_up_to_depth($max_depth - 1)) elif type == "array" then map(keep_up_to_depth($max_depth - 1)) else . end) end; keep_up_to_depth(3)' data.json
输出结果
执行后会得到截断后的JSON,仅保留前3层结构:
{ "Service1": { "Production": { "Location 1": {}, "Service2": { "Production": { "Location 1": {} } } } } }
原理说明
- 函数
keep_up_to_depth($max_depth)接收参数$max_depth,表示从根节点开始要保留的层级数。 - 当递归到
$max_depth == 0时,将对象/数组替换为空结构,字符串、数字等基础类型保持不变。 - 未达到指定深度时,递归处理对象的每个键值对或数组的每个元素,层级数逐层递减。
内容的提问来源于stack exchange,提问作者Haim Marko
相关产品推荐
相关产品推荐

