在Shell
脚本中处理请求返回的JSON
数据是一个常见的任务,尤其是在自动化脚本和API交互中。当使用curl
发送HTTP
请求,然后结合jq
或Python
来解析和处理返回的JSON数据。
方法一 curl
和jq
response=$(curl -s 'https://api.test.com/data')
# 使用 jq 提取某个字段
name=$(echo "$response" | jq -r '.user.name')
echo "Name: $name"
# 提取数组中的所有值
emails=$(echo "$response" | jq -r '.user.contacts[] | select(.type == "email") | .value')
echo "Emails: $emails"
方法二 curl
和Python
response=$(curl -s 'https://api.test.com/data')
# 使用 Python 提取某个字段
name=$(echo "$response" | python -c "
import sys, json
data = json.load(sys.stdin)
print(data['user']['name'])
")
echo "Name: $name"
# 提取数组中的所有值
emails=$(echo "$response" | python -c "
import sys, json
data = json.load(sys.stdin)
emails = [c['value'] for c in data['user']['contacts'] if c['type'] == 'email']
print(', '.join(emails))
")
echo "Emails: $emails"
方法三、curl
和grep
/sed
/awk
response=$(curl -s 'https://api.test.com/data')
# 提取简单字段
name=$(echo "$response" | grep -oP '"name":\s*"\K[^"]+')
echo "Name: $name"
# 提取数组中的值
emails=$(echo "$response" | grep -oP '"type":\s*"email".*?"value":\s*"\K[^"]+')
echo "Emails: $emails"