Skip to content

Instantly share code, notes, and snippets.

@airglow923
Last active January 2, 2021 15:12
Show Gist options
  • Select an option

  • Save airglow923/83849aca55e18d93e7067c2537533bad to your computer and use it in GitHub Desktop.

Select an option

Save airglow923/83849aca55e18d93e7067c2537533bad to your computer and use it in GitHub Desktop.
jq but edit json inplace
#!/bin/sh
# The first argument should be json string that would be fed into jq.
# The second argument should be json filename.
# create temporary file
TEMP=$(mktemp)
# remove temoorary file in case the program terminates unexpectedly
trap "{ rm -f $TEMP; }" EXIT
# redirect the result of jq [FIRST ARG] [SECOND ARG] to temporary file
jq "$1" "$2" > $TEMP
# replace original json with new one
cat $TEMP > "$2"
# remove used temporary file
rm $TEMP
@airglow923
Copy link
Author

Example usage:

sample.json

{
  "scripts": {
    "test": "Placeholder"
  }
}

Command:
./jq-inplace.sh '.scripts += {"build": "tsc", "test": "another text"}' sample.json

modified sample.json

{
  "scripts": {
    "test": "another text",
    "build": "tsc"
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment