从 JSON 获取数组对象并循环列表

问题描述 投票:0回答:1

我需要使用 GitHub Actions 工作流程,该工作流程将执行 API 调用以获取 ID 列表,然后循环遍历 ID 列表并使用其中的每一个执行 API POST。

我遇到的问题是 API 返回多个数组对象,而我无法仅访问数组对象。

作业 1 (define-matrix) 中的“json-project”是第一次 API 调用返回的示例。

---
name: Test Loop
on:
  push:
    branches: [development]
    
jobs:
  # Job 1: Collect data
  define-matrix:
    runs-on: ubuntu-latest

    outputs:
      json-project: ${{ steps.project-step.outputs.json-project }}

    steps:
      - name: Define Project String
        id: project-step
        run: |
          echo "json-project={\"count\":2,\"include\":[{\"project\":\"1\",\"config\":\"Debug\"},{\"project\":\"2\",\"config\":\"Release\"}]}" >> "$GITHUB_OUTPUT"
        

  # Job 2: Print the output of the "define-matrix" job
  print-output:
    runs-on: ubuntu-latest
    needs: define-matrix
      
    steps:
      - name: Print project-json variable
        id: print-stuff
        run: |
          echo ${{ toJson(needs.define-matrix.outputs.json-project) }}
          echo ${{ toJson(needs.define-matrix.outputs.json-project) }} | jq -r '.include[].project'

  # Job 3: Loop through array
  print-array-output:
    runs-on: ubuntu-latest
    needs: define-matrix

    strategy:
      matrix: ${{ fromJson(needs.define-matrix.outputs.json-project) }}
      
    steps:
      - name: Print project-json variable
        id: print-array-item
        run: |
          curl --insecure --request POST --url ${{ vars.url }}/projects/${{ matrix.include.project }}/update/


当我运行此作业时,作业 3(打印数组输出)返回以下错误:

Error when evaluating 'strategy' for job 'print-array-output'. .github/workflows/test-loop2.yml (Line: 40, Col: 15): Unexpected value '2'

这似乎是错误的,因为“count”对象位于“include”数组的前面。但我不知道如何让策略/矩阵仅使用“包含”对象。

有人可以提供建议吗?

json github-actions
1个回答
0
投票

您可以使用 属性解引用运算符

.
fromJson
来仅获取
include
数组并直接设置
strategy.matrix.include
,如下所示:

strategy:
  matrix:
    include: ${{ fromJson(needs.define-matrix.outputs.json-project).include }}

,稍后使用

matrix.project
matrix.config
访问这些值。

这是更新后的工作流程:

name: matrix_test

on: workflow_dispatch

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: echo 'json-project={"count":2,"include":[{"project":"1","config":"Debug"},{"project":"2","config":"Release"}]}' >>"$GITHUB_OUTPUT"

  print-output:
    runs-on: ubuntu-latest
    needs: define-matrix

    steps:
      - name: Print project-json variable
        run: echo '${{ needs.define-matrix.outputs.json-project }}' | jq -r '.include[].project'

  print-array-output:
    runs-on: ubuntu-latest
    needs: define-matrix

    strategy:
      matrix:
        include: ${{ fromJson(needs.define-matrix.outputs.json-project).include }}

    steps:
      - name: Print project-json variable
        run: echo '${{ matrix.project }} | ${{ matrix.config }}'
© www.soinside.com 2019 - 2024. All rights reserved.