【问题标题】:Edit the value inside the JSON array with Github Actions使用 Github Actions 编辑 JSON 数组中的值
【发布时间】:2023-03-08 22:15:01
【问题描述】:

我有一个这样的 JSON 存储在执行我的 Github 操作的文件夹/路径中 -

{
   "version":"1",
   "sampleArray":[
      {
         "id":"1"
      }
   ],
   "secondArray":[
      {
         "secondId":"2"
      }
   ]
}

使用 Github 操作如何编辑 id 的值,例如:将 id 的值设置为 sampleArray 内的“5”,以便我的 JSON 具有更新的值?

【问题讨论】:

  • 您可以使用大多数 linux 发行版中可用的 jq 命令,但这取决于构建时选择的映像。
  • @SamridhTuladhar 你能举个例子吗

标签: javascript json github continuous-integration github-actions


【解决方案1】:

您可以使用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"
    }]
}

【讨论】:

  • 感谢您的回答 :) 但是 echo "jq '.sampleArray[0].id="5"' config.json" > config.json 正在将 json 文件修改为空。
  • @Maria 上面的两个解决方案在 github 操作中都为我工作,日志中是否有任何错误?也许它与你的 json vs jq 查询的结构有关 screenshot
猜你喜欢
  • 2022-07-13
  • 2020-04-14
  • 2020-03-29
  • 2022-10-17
  • 2021-05-10
  • 1970-01-01
  • 1970-01-01
  • 2020-09-07
  • 2019-10-29
相关资源
最近更新 更多