Auto-learner
Auto-learner

Reputation: 1511

SED/AWK how to replace a value if a parent key matches in json file

I'm trying to replace the default value if the parent is refreshinterval.I have tried using jq and sed but unable to get my expected output. Can someone help to get the expected answer.

{ "doubleClickDiff": {
        "type": "boolean",
        "title": "Show diff on double click",
        "description": "If true, doubling clicking a file in the list of changed files will open a diff.",
        "default": false
      },
      "historyCount": {
        "type": "integer",
        "title": "History count",
        "description": "Number of (most recent) commits shown in the history log",
        "default": 25
      },
      "refreshInterval": {
        "type": "integer",
        "title": "Refresh interval",
        "description": "Number of milliseconds between polling the file system for changes.",
        "default": 10000
      },
      "simpleStaging": {
        "type": "boolean",
        "title": "Simple staging flag",
        "description": "If true, use a simplified concept of staging. Only files with changes are shown (instead of showing staged/changed/untracked), and all files with changes will be automatically staged",
        "default": false
      }}

my output should replace default value only if key is refreshInterval

"refreshInterval": {
        "type": "integer",
        "title": "Refresh interval",
        "description": "Number of milliseconds between polling the file system for changes.",
        "default": 40000
      },



jq '."refreshInterval"."default"=40000' plugin.json

sed -i 's/\"default\":.*/\"default\": '40000'/g' "demo.json"

Upvotes: 0

Views: 394

Answers (1)

Aaron
Aaron

Reputation: 24802

The jq command you've posted should work just fine, but it doesn't update the file, it just outputs the updated result. You can store that output and overwrite the original file with it as follows :

jq '.refreshInterval.default = 40000' plugin.json > jq_output
mv jq_output plugin.json

Careful not to try to simplify it into jq '.refreshInterval.default = 40000' plugin.json > plugin.json as the redirection will be processed first and erase the content of the file before jq can read it. If you want to avoid the use of a temporary file you could use an utility such as sponge from the moreutils package which allows in-place edition.

Upvotes: 2

Related Questions