我想读取JSON文件并在Github Actions YAML文件的字符串中使用属性。我该怎么做呢?
(我需要package.json
的版本)
答案 0 :(得分:7)
使用内置的fromJson(value)
(请参见此处:https://help.github.com/en/actions/reference/context-and-expression-syntax-for-github-actions#fromjson)
读取文件取决于您使用的Shell。这是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}}"
根据https://github.community/t5/GitHub-Actions/set-output-Truncates-Multiline-Strings/td-p/37870
的多行JSON处理关于set-env
/ set-output
多行处理的GitHub问题:https://github.com/actions/toolkit/issues/403
答案 1 :(得分:1)
下面是Official GHA Docs中示例的一个版本,其中包括两个更改:
./your.json
)中加载json name: build
on: push
jobs:
job1:
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.set-matrix.outputs.matrix }}
steps:
- id: set-matrix
run: |
JSON=$(cat ./your.json)
echo "::set-output name=${JSON//'%'/'%25'}"
job2:
needs: job1
runs-on: ubuntu-latest
strategy:
matrix: ${{fromJson(needs.job1.outputs.matrix)}}
steps:
- run: build
答案 2 :(得分:0)
我曾经用它来获取json数据的值。希望对您有帮助
- name: fetch the json value
run: |
githubjson=`cat $GITHUB_EVENT_PATH`
echo $githubjson
number=`echo $(jq -r '.number' <<< "$githubjson")`
PRTitle=`echo $(jq -r '.pull_request.title' <<< "$githubjson")`
PRUrl=`echo $(jq -r '.pull_request.html_url' <<< "$githubjson")`
PRBody=`echo $(jq -r '.pull_request.body' <<< "$githubjson")`
答案 3 :(得分:0)
on: [push, pull_request]
name: Build
jobs:
build:
name: Example
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
path: './'
- run: |
echo "`jq '.base_config[0].value="Alpha-21"' config.json `" > config.json
echo "`jq '.base_config[1].value="1.2.14"' config.json`" > config.json
echo "`jq '.base_config[2].value="29/12/2020"' config.json `" > config.json
- uses: EndBug/add-and-commit@v6
with:
message: 'Add the version and date'
add: '*.json --force'
cwd: './'
token: ${{ secrets.TOKEN }}