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

如何在Bash中用jq的walk函数捕获嵌套键值到变量?

Bash中捕获jq输出到变量 + 用walk提取任意嵌套键值

Hey there! Glad you're getting comfortable with jq thanks to @peak's help—let's break down the two issues you're stuck on, step by step.

1. 捕获jq输出到Bash变量

This is super straightforward once you get the hang of command substitution in Bash. Here are common scenarios:

捕获单个字符串值

Use $(...) to capture the output, and add the -r flag to jq to get raw output (without surrounding quotes):

# 示例1:从字符串JSON中提取值
json='{"user": {"profile": {"name": "Alice"}}}'
name=$(echo "$json" | jq -r '.user.profile.name')
echo "Captured name: $name"  # 输出 Captured name: Alice

# 示例2:从JSON文件中提取值
name=$(jq -r '.user.profile.name' user_data.json)

捕获数组/复杂JSON结构

If you need to capture a full JSON object or array, skip the -r flag (or use -c for compact output) to preserve the JSON format:

json='{"items": ["apple", "banana", "cherry"]}'
items=$(echo "$json" | jq -c '.items')
echo "Captured items: $items"  # 输出 Captured items: ["apple","banana","cherry"]

2. 用walk(或更简洁的方法)提取任意嵌套的目标键值

Since your JSON structure is unknown and the target key could be 0-20 levels deep, you have two solid approaches:

方法1:用walk()遍历所有节点

The walk() function recursively iterates over every element in your JSON. We can check if an element is an object that contains our target key, then extract its value:

# 假设目标键是"target_key"
json='{"level1": {"target_key": "val1"}, "level2": {"level3": {"target_key": "val2"}}, "target_key": "val3"}'
# 提取所有target_key的值,每行一个
all_values=$(echo "$json" | jq -r 'walk(if type == "object" and has("target_key") then .target_key else . end)')
echo "$all_values"
# 输出:
# val1
# val2
# val3

方法2:用递归遍历[..](更简洁)

A common alternative to walk() is using [..] to recursively traverse all nodes, then filter for objects with your target key:

# 把所有值收集到一个JSON数组中
values_array=$(echo "$json" | jq -c '[.. | objects | select(has("target_key")) | .target_key]')
echo "$values_array"  # 输出 ["val1","val2","val3"]

This method is often more readable for this specific use case, as it directly targets objects with your key across all nesting levels.

注意事项

  • Replace "target_key" with your actual key name in all examples.
  • If your target key has special characters (like spaces), wrap it in quotes: has("my special key") or ."my special key".

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:49:24