Set a value in place with jq

19 Jul 2021 in TIL

How to edit a JSON file in place with `jq`

I recently needed to set a value in a JSON file. Using jq I can do this by setting the value directly like so:

bash
jq '.scripts.build = "npx @vercel/ncc build && npx convert-action"' package.json

However, this returns the file contents rather than editing the file in place. To update a file's contents without a temporary file you need to use cat and a sub-shell:

bash
cat <<< "$(jq '.scripts.build = "npx @vercel/ncc build && npx convert-action"' package.json)" > package.json

This will set .scripts.build in package.json in-place.

I discovered this whilst contributing to build-and-tag-action