GitHub Actions矩阵配置报错:如何仅使用返回的include数组?
解决GitHub Actions矩阵读取嵌套数组的问题
问题场景
需要通过GitHub Actions实现:调用API获取ID列表,遍历列表为每个ID发起POST请求。但API返回的JSON包含count和include两个字段,使用该JSON作为矩阵配置时触发错误:
Error when evaluating 'strategy' for job 'print-array-output'. .github/workflows/test-loop2.yml (Line: 40, Col: 15): Unexpected value '2'
原因是矩阵解析时识别到了count字段,而该字段不符合矩阵的配置规则,我们需要仅提取include中的数组作为矩阵数据源。
解决方案
有两种可行方案,核心都是让矩阵仅读取include数组:
方案1:在数据收集阶段直接输出include数组
修改Job1(define-matrix)的输出逻辑,只提取JSON中的include部分:
jobs: define-matrix: runs-on: ubuntu-latest outputs: json-project: ${{ steps.project-step.outputs.json-project }} steps: - name: Define Project String id: project-step run: | # 模拟API返回的JSON API_RESPONSE='{"count":2,"include":[{"project":"1","config":"Debug"},{"project":"2","config":"Release"}]}' # 提取include数组并输出 echo "json-project=$(echo "$API_RESPONSE" | jq -c '.include')" >> "$GITHUB_OUTPUT"
此时Job3的矩阵可以直接使用该输出:
print-array-output: runs-on: ubuntu-latest needs: define-matrix strategy: matrix: ${{ fromJson(needs.define-matrix.outputs.json-project) }} steps: - name: Send POST request run: | curl --insecure --request POST --url ${{ vars.url }}/projects/${{ matrix.project }}/update/
方案2:在矩阵配置阶段直接读取include字段
无需修改Job1,直接在Job3的矩阵配置中通过JSON路径提取include数组:
print-array-output: runs-on: ubuntu-latest needs: define-matrix strategy: matrix: ${{ fromJson(needs.define-matrix.outputs.json-project).include }} steps: - name: Send POST request run: | curl --insecure --request POST --url ${{ vars.url }}/projects/${{ matrix.project }}/update/
说明
GitHub Actions的矩阵策略接受两种格式:
- 直接的数组(如
[{"project":"1"},...]) - 包含
include字段的对象(如{"include": [...]})
原错误是因为传入的JSON包含count这个非矩阵合法字段,导致解析失败。上述两种方案都确保矩阵仅获取include中的数组数据,从而正常遍历执行。
内容的提问来源于stack exchange,提问作者rcart
相关产品推荐
相关产品推荐

