如何在GitLab Pipeline中用jq遍历JSON并添加HTTP响应字段?
解决GitLab Pipeline中为JSON子对象添加HTTP响应字段的方法
场景1:直接在jq中调用curl获取状态码(推荐)
如果无需提前缓存状态码,可直接遍历JSON的每个条目,调用curl获取状态码并添加字段:
假设原JSON结构(数组型):
{ "services": [ {"name": "auth", "path_to_file": "https://your-domain/auth/health"}, {"name": "payment", "path_to_file": "https://your-domain/payment/health"} ] }
Pipeline脚本命令:
# 确保jq和curl已安装(根据Runner镜像调整,Alpine用apk,Debian/Ubuntu用apt) apk add --no-cache jq curl # 处理JSON,添加http_response字段 jq '.services |= map( .http_response = ( "curl -s -m 5 -o /dev/null -w \"%{http_code}\"" + .path_to_file | sh | tonumber ) )' input.json > output.json
场景2:已提前获取状态码数组,合并到JSON
如果已经通过其他方式把状态码存到bash数组status_codes中,可按以下步骤合并:
脚本命令:
# 将bash数组转换为JSON数组 status_json=$(printf '%s\n' "${status_codes[@]}" | jq -R . | jq -s .) # 合并原JSON与状态码数组,添加字段 jq --argjson statuses "$status_json" '.services |= zip($statuses) | map(.[0] + {http_response: .[1]|tonumber})' input.json > output.json
场景3:原JSON是对象结构(非数组)
如果你的JSON是键值对形式的对象,而非数组:
{ "auth_service": {"path_to_file": "https://your-domain/auth/health"}, "payment_service": {"path_to_file": "https://your-domain/payment/health"} }
处理命令:
jq 'to_entries | map( .value.http_response = ( "curl -s -m 5 -o /dev/null -w \"%{http_code}\"" + .value.path_to_file | sh | tonumber ) ) | from_entries' input.json > output.json
关键说明
sh函数:jq中用于执行shell命令,返回命令输出结果,仅jq 1.6及以上版本支持- 超时参数:
curl -m 5设置5秒超时,避免Pipeline因请求卡住 - 类型转换:
tonumber将字符串状态码转为数字类型,可根据需求省略
内容的提问来源于stack exchange,提问作者Bisteccowner
相关产品推荐
相关产品推荐

