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
)
Run jq is not certified by GitHub.
GitHub Actions Documentation Automate, customize, and execute your software development workflows right in your repository with GitHub Actions. You can discover, create, and share actions to perform any job you'd like, including CI/CD, and combine actions in a completely customized workflow.
- run: call some https endpoint > at.json - run: echo "AUTH_TOKEN= $ (jq '.authorizationToken' at.json)" >> $GITHUB_ENV - run: echo "$ { { env.AUTH_TOKEN }}" Line 1: some command which calls some external service via HTTPS. Response payload is JSON. this json data is then stored straight away into a file called at.json.
The secrets that you create are available to use in GitHub Actions workflows. GitHub uses a libsodium sealed box to help ensure that secrets are encrypted before they reach GitHub and remain encrypted until you use them in a workflow.
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.community/t5/GitHub-Actions/set-output-Truncates-Multiline-Strings/td-p/37870
GitHub issue about set-env
/ set-output
multi line handling: https://github.com/actions/toolkit/issues/403
Use a multi line environment variable:
- run: |
echo 'PACKAGE_JSON<<EOF' >> $GITHUB_ENV
cat ./package.json >> $GITHUB_ENV
echo 'EOF' >> $GITHUB_ENV
- run: |
echo '${{ fromJson(env.PACKAGE_JSON).version }}'
This avoids any need for escaping.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With