less than 1 minute read

I’m a huge fan of jq, a JSON parser for the command line. It’s great for reading elements from a JSON file:

> jq '.debug.savePayload' file.json

And for creating a new file by adding elements to an existing file:

jq '. + {"name": "Francis"}' file.json > file2.json

Unfortunately, jq doesn’t support adding elements to an existing file out of the box. To do this, you can use sponge:

# brew install moreutils  # If necessary.
jq '. + {"name": "Francis"}' file.json | sponge file.json

From the user manual:

sponge reads standard input and writes it out to the specified file. Unlike a shell redirect, sponge soaks up all its input before opening the output file. This allows constricting pipelines that read from and write to the same file.

If no output file is specified, sponge outputs to stdout.

Tags: ,