jsonyamlgithub-actions

Read JSON file in GitHub Actions


I want to read a JSON file and use a property in a string in a GitHub Actions YAML file. How do I do this? (I want the version of the package.json.)


Solution

  • Use the built-in fromJson(value) (see here: https://docs.github.com/en/actions/learn-github-actions/expressions#fromjson)

    Reading a file depends on the shell you're using. Here's an example for sh:

    name: Test linux job
    on:
      push
    
    jobs:
      testJob:
        name: Test
        runs-on: ubuntu-latest
        steps:
          - id: set_var
            run: |
              content=`cat ./path/to/package.json`
              # the following lines are only required for multi line json
              content="${content//'%'/'%25'}"
              content="${content//$'\n'/'%0A'}"
              content="${content//$'\r'/'%0D'}"
              # end of optional handling for multi line json
              echo "::set-output name=packageJson::$content"
          - run: |
              echo "${{fromJson(steps.set_var.outputs.packageJson).version}}"
    
    

    Multi line JSON handling as per https://github.com/orgs/community/discussions/26288#discussioncomment-3251220.

    GitHub issue about set-env / set-output multi line handling: https://github.com/actions/toolkit/issues/403