Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Edit the value inside the JSON array with Github Actions

I have a JSON like this stored in the folder/path where my Github action is executed -

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

Using Github actions how can I edit the value of id eg: make the id value as "5" inside the sampleArray so that my JSON has an updated value?

like image 443
Ma2340 Avatar asked Jun 26 '26 07:06

Ma2340


1 Answers

You can use jq command line tool to edit the json file in place like this :

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

You can also use it with sponge from the moreutils package and pass an environment variable in the following example :

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

which would output :

{
    "version": "1",
    "sampleArray": [{
        "id": "5"
    }],
    "secondArray": [{
        "secondId": "2"
    }]
}
like image 86
Bertrand Martel Avatar answered Jun 27 '26 21:06

Bertrand Martel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!