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

Github Actions:处理JSON中右括号跨步骤传递的问题

解决GitHub Actions中JSON含右括号导致的Shell语法错误

问题背景

调用GitHub API获取工作流运行数据后,用Shell脚本结合jq解析结果时,若返回的JSON中包含右括号)(比如提交消息里的message with a )),会触发Shell语法错误。这是因为GitHub上下文变量展开后,里面的)会跳出单引号包裹的范围,导致Shell提前结束命令替换或变量赋值,报错类似syntax error near unexpected token ')'或timestamp:: command not found。

可行解决方案

方案1:用GitHub Actions的fromJSON直接在上下文层面解析

GitHub Actions支持用fromJSON表达式直接解析JSON输出,无需将完整JSON传入Shell,从根源避免特殊字符问题。

- uses: octokit/request-action@v2.x
  id: get_in_progress_workflow_run
  with:
    route: GET /repos/myorg/myrepo/actions/runs?page=1&per_page=20
  env:
    GITHUB_TOKEN: ${{ secrets.ACCESS_TOKEN }}
- name: Get waiting pull_request_id
  id: get_pr_id
  run: |
    echo "prId=${{ fromJSON(steps.get_in_progress_workflow_run.outputs.data).workflow_runs | first(select(.status == 'in_progress')).pull_requests[0].number }}" >> "$GITHUB_OUTPUT"

方案2:通过环境变量传递JSON数据

将JSON内容赋值给环境变量,Shell读取环境变量时会正确保留所有特殊字符,不会触发语法错误。

- uses: octokit/request-action@v2.x
  id: get_in_progress_workflow_run
  with:
    route: GET /repos/myorg/myrepo/actions/runs?page=1&per_page=20
  env:
    GITHUB_TOKEN: ${{ secrets.ACCESS_TOKEN }}
- name: Get waiting pull_request_id
  id: get_pr_id
  env:
    WORKFLOW_RUNS_DATA: ${{ steps.get_in_progress_workflow_run.outputs.data }}
  run: |
    prId="$(echo "$WORKFLOW_RUNS_DATA" | jq '.workflow_runs[] | first(select(.status=="in_progress")) | .pull_requests[0] | .number')"
    echo "prId=$prId" >> "$GITHUB_OUTPUT"

方案3:用printf替代echo传递JSON字符串

printf对特殊字符的处理更稳定,能原样输出包含)的JSON内容,避免Shell解析异常。

- uses: octokit/request-action@v2.x
  id: get_in_progress_workflow_run
  with:
    route: GET /repos/myorg/myrepo/actions/runs?page=1&per_page=20
  env:
    GITHUB_TOKEN: ${{ secrets.ACCESS_TOKEN }}
- name: Get waiting pull_request_id
  id: get_pr_id
  run: |
    prId="$(printf '%s' '${{ steps.get_in_progress_workflow_run.outputs.data }}' | jq '.workflow_runs[] | first(select(.status=="in_progress")) | .pull_requests[0] | .number')"
    echo "prId=$prId" >> "$GITHUB_OUTPUT"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 00:10:51