使用 Github 操作编辑 JSON 数组中的值
Edit the value inside the JSON array with Github Actions
我有一个像这样的 JSON 存储在执行我的 Github 操作的 folder/path 中 -
{
"version":"1",
"sampleArray":[
{
"id":"1"
}
],
"secondArray":[
{
"secondId":"2"
}
]
}
使用 Github 操作如何编辑 id
的值,例如:将 id
的值设为 sampleArray
中的“5”,以便我的 JSON 有更新值?
您可以使用 jq 命令行工具就地编辑 json 文件,如下所示:
on: [push, pull_request]
name: Build
jobs:
build:
name: Example
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Update config.json
run: echo "`jq '.sampleArray[0].id="5"' config.json`" > config.json
- name: read config.json
run: cat config.json
您还可以将它与 moreutils 包中的 sponge 一起使用,并在以下示例中传递环境变量:
on: [push, pull_request]
name: Build
jobs:
build:
name: Example
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: install more-utils
run: sudo apt-get install moreutils
- name: Update config.json
env:
ID: 5
run: jq --arg id "$ID" '.sampleArray[0].id=$id' config.json | sponge config.json
- name: read config.json
run: cat config.json
这将输出:
{
"version": "1",
"sampleArray": [{
"id": "5"
}],
"secondArray": [{
"secondId": "2"
}]
}
我有一个像这样的 JSON 存储在执行我的 Github 操作的 folder/path 中 -
{
"version":"1",
"sampleArray":[
{
"id":"1"
}
],
"secondArray":[
{
"secondId":"2"
}
]
}
使用 Github 操作如何编辑 id
的值,例如:将 id
的值设为 sampleArray
中的“5”,以便我的 JSON 有更新值?
您可以使用 jq 命令行工具就地编辑 json 文件,如下所示:
on: [push, pull_request]
name: Build
jobs:
build:
name: Example
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Update config.json
run: echo "`jq '.sampleArray[0].id="5"' config.json`" > config.json
- name: read config.json
run: cat config.json
您还可以将它与 moreutils 包中的 sponge 一起使用,并在以下示例中传递环境变量:
on: [push, pull_request]
name: Build
jobs:
build:
name: Example
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: install more-utils
run: sudo apt-get install moreutils
- name: Update config.json
env:
ID: 5
run: jq --arg id "$ID" '.sampleArray[0].id=$id' config.json | sponge config.json
- name: read config.json
run: cat config.json
这将输出:
{
"version": "1",
"sampleArray": [{
"id": "5"
}],
"secondArray": [{
"secondId": "2"
}]
}