Toolarity

jq Edit JSON In Place: Update a File Without Emptying It

Fix jq Published November 11, 2026

You want to change one value in a JSON file with jq, so you write jq '.port = 9090' config.json > config.json. It prints nothing, exits 0, and your config file is now empty. jq has no -i option like sed -i, so writing the result back is your job, and the usual one-liner for it has more holes than the one it replaces.

I ran every command below on three jq builds: the two official releases listed in the box above (checksums matched each release’s sha256sum.txt) and the jq that ships in /usr/bin on macOS. All output is copied from the terminal, and a script re-runs each block against a fresh copy of the test files on all three builds. They behaved the same everywhere except one place, which is the most dangerous one: macOS’s built-in jq exits 0 when it can’t parse the file.

Short answer (tested 2026-09-30): write to a temporary file, and only copy it back if jq succeeded, printed no errors and produced output. This function does that and keeps the file’s permissions and symlinks:

# jq_inplace FILTER FILE [jq options...]
# Writes the result back only if jq exited 0, printed nothing
# on stderr, and produced non-empty output.
jq_inplace() {
  local filter=$1 file=$2 tmp err
  shift 2
  tmp=$(mktemp "$file.XXXXXX") || return 1
  err=$(jq "$@" "$filter" "$file" 2>&1 >"$tmp")
  if [ $? -ne 0 ] || [ -n "$err" ] || [ ! -s "$tmp" ]; then
    [ -n "$err" ] && printf '%s\n' "$err" >&2
    echo "jq_inplace: $file left unchanged" >&2
    rm -f "$tmp"
    return 1
  fi
  cat "$tmp" > "$file"
  rm -f "$tmp"
}
What you ranWhat happened to the fileFix
jq … f.json > f.jsonEmpty, exit code 0Never redirect into the input
jq … f.json | tee f.jsonEmpty in every one of my 300 runsSame
jq … > tmp && mv tmp f.json, filter output nothingEmpty, exit code 0Check the temp file isn’t empty
Same, file has a comment or trailing comma, macOS /usr/bin/jqEmpty, exit code 0Check stderr, or use an official release
Same, file is mode 600 or a symlinkNow 644; symlink replaced by a plain fileCopy the content back instead of mv
Same, filter was .items[] | select(…) | .x = 1Replaced by the one matching itemWrap the path: (.items[] | select(…) | .x) = 1
--arg n 9090 '.port = $n'"port": "9090", a string--argjson n 9090

The test file

config.json, indented with four spaces, with a price that has a trailing zero, an ID bigger than 2^53, and an escaped é:

{
    "name": "demo",
    "port": 8080,
    "price": 1.50,
    "id": 9007199254740993,
    "note": "café",
    "items": [
        {"name": "a", "price": 1},
        {"name": "b", "price": 2}
    ]
}

Next to it: settings.json (a hand-edited config with a // comment), two.json (two JSON values, the second one cut off), dup.json (a repeated key), a.json and b.json ({"a": 1} and {"a": 2}), and link.json, a symlink to real/config.json. Both config.json files are chmod 600, the way you’d keep a file with secrets.

Why > config.json empties the file

The shell opens config.json for writing, and truncates it, before jq starts. jq then reads an empty file. Empty input isn’t an error to jq, so there’s no message and the exit code is 0:

$ jq '.port = 9090' config.json > config.json
$ echo $?
0
$ [ -s config.json ] || echo "config.json is empty"
config.json is empty

Piping through tee config.json is the same race with extra steps: tee truncates the file while jq may still be reading it. The official jq FAQ says it’s “not recommended, even if it seems to work.” It didn’t even seem to work for me: I ran jq '.z = 1' w.json | tee w.json 50 times per build, on a 9-byte file and on a 1.4 MB file, and all 300 runs left an empty file.

The usual fix, and the four ways it still loses data

The FAQ’s recommendation is a temporary file: jq ... input.json > tmp.json && mv tmp.json input.json. The && means mv only runs if jq’s exit code is 0. That works as long as “exit code 0” means “the output is your whole file”, and it often doesn’t.

1. The filter produced no output

select() that matches nothing makes jq print nothing and still exit 0. Here the file’s name is demo, not prod:

$ jq 'select(.name == "prod") | .port = 9090' config.json > tmp.json && mv tmp.json config.json
$ echo $?
0
$ [ -s config.json ] || echo "config.json is empty"
config.json is empty

Adding -e makes jq exit 4 when there’s no output, so mv doesn’t run. That saves this case, but not the next one. Checking that the temp file isn’t empty ([ -s tmp.json ]) covers both.

2. The file doesn’t parse, and you’re on macOS’s built-in jq

JSON doesn’t allow comments or trailing commas, but plenty of hand-edited config files have them. The official releases print a parse error and exit 5, so mv never runs:

$ jq '.a = 2' settings.json > tmp.json && mv tmp.json settings.json
jq: parse error: Invalid numeric literal at line 2, column 5
$ echo $?
5
$ cat settings.json
{
  // comment
  "a": 1
}

The jq in /usr/bin on macOS prints the same error, then exits 0. mv runs and moves the empty temp file over your config:

$ /usr/bin/jq '.a = 2' settings.json > tmp.json && mv tmp.json settings.json
jq: parse error: Invalid numeric literal at line 2, column 5
$ echo $?
0
$ [ -s settings.json ] || echo "settings.json is empty"
settings.json is empty

-e doesn’t fully save you here either. With -e, the macOS build exits 4 on settings.json, but on two.json it outputs the first value, prints a parse error for the second (hidden here with 2>/dev/null) and exits 0, so the file would be overwritten with only the first value:

$ /usr/bin/jq -e -c '.a = 5' two.json 2>/dev/null; echo "exit $?"
{"a":5}
exit 0

An empty-file check doesn’t catch that one; a non-empty stderr does. Old jq releases getting exit codes wrong on bad input is known history (jq issue #1161, where a jq contributor says it was fixed in a 2018 release); macOS still ships a build that behaves this way. Run jq --version to see which one you’re calling. If the version string contains apple, it’s the built-in one.

mv doesn’t write into your file; it replaces it with the temp file, which was created with your default permissions. A chmod 600 file becomes readable by everyone on the machine. And if the path was a symlink, the symlink is gone, replaced by a regular file, while the file it pointed to is never updated:

$ stat -f '%Sp %N%SY' config.json link.json
-rw------- config.json
lrwxr-xr-x link.json -> real/config.json
$ jq '.port = 9090' config.json > tmp.json && mv tmp.json config.json
$ jq '.port = 9090' link.json > tmp.json && mv tmp.json link.json
$ stat -f '%Sp %N%SY' config.json link.json real/config.json
-rw-r--r-- config.json
-rw-r--r-- link.json
-rw------- real/config.json
$ jq .port real/config.json
8080

(stat -f is the macOS form; on Linux, ls -l shows the same thing.) This matters for dotfiles kept as symlinks and for config files that hold tokens.

Copying the content back with cat tmp.json > config.json writes through the symlink and keeps the mode, which is what the function above does. The trade-off: mv swaps the file in one step, while cat rewrites it, so a program reading the file at that exact moment could see it half-written. For a config file you edit by hand, keeping the permissions matters more. If something reads the file constantly, use mv and fix the mode and the path yourself.

4. The filter returned a piece, not the whole document

This is the one that looks right in the terminal. You want to change one item’s price:

$ jq '.items[] | select(.name == "b") | .price = 5' config.json > tmp.json && mv tmp.json config.json
$ cat config.json
{
  "name": "b",
  "price": 5
}

jq did exactly what the pipe says: go into the items, keep b, set its price, and output that. Everything else in the file is gone. Put the whole path on the left of =, in parentheses, and jq returns the whole document with that spot changed:

$ jq '(.items[] | select(.name == "b") | .price) = 5' config.json > tmp.json && mv tmp.json config.json
$ jq -c '.items' config.json
[{"name":"a","price":1},{"name":"b","price":5}]

No exit code or size check can catch this one, the function above included. The habit that does: run the filter without writing first and look at the first line of output. If it isn’t the top of your file, don’t write it.

Using the function

jq_inplace takes the filter, then the file, then any jq options:

$ jq_inplace '.port = 9090' link.json
$ stat -f '%Sp %N%SY' link.json real/config.json
lrwxr-xr-x link.json -> real/config.json
-rw------- real/config.json
$ jq .port real/config.json
9090
$ jq_inplace '.port = $p' config.json --argjson p 7070
$ jq .port config.json
7070

The failures from above all leave the file alone and return 1:

$ jq_inplace 'select(.name == "prod") | .port = 1' config.json
jq_inplace: config.json left unchanged
$ echo $?
1
$ jq_inplace '.a = 2' settings.json
jq: parse error: Invalid numeric literal at line 2, column 5
jq_inplace: settings.json left unchanged
$ jq_inplace '.a = 5' two.json
jq: parse error: Unfinished JSON term at EOF at line 3, column 0
jq_inplace: two.json left unchanged
$ ls
a.json
b.json
config.json
dup.json
link.json
real
settings.json
two.json

No temp files are left behind. It does the same on all three builds, including the macOS one, because it checks stderr instead of trusting the exit code. The one downside: if your filter uses debug or stderr on purpose, that output counts as an error. It also can’t catch mistake 4.

--arg writes a string

--arg always passes a string, so a number you pass in gets quoted in the file:

$ jq --arg p 9090 '.port = $p | .port' config.json
"9090"
$ jq --argjson p 9090 '.port = $p | .port' config.json
9090
$ jq --arg p 9090 '.port = ($p | tonumber) | .port' config.json
9090

Use --argjson for numbers, true/false and null. It also takes whole objects and arrays, as long as the text is valid JSON.

What else changes when jq rewrites the file

Your one-value edit rewrites every line. On all three builds, key order stayed as it was, and numbers I didn’t touch kept their exact text (1.50, and the 16-digit ID). These did change:

$ jq '.port = 9090' config.json > tmp.json && mv tmp.json config.json
$ head -4 config.json
{
  "name": "demo",
  "port": 9090,
  "price": 1.50,
$ grep note config.json
  "note": "café",
  • Indentation becomes two spaces. --indent 4 or --tab gets you back to your indent width, but objects that were on one line (like the items here) still get spread over several lines, so the diff won’t be only your change.
  • Escapes like é are written as the character itself. -a escapes all non-ASCII characters, which keeps this one but also escapes any that were written as plain characters.
  • Doing arithmetic on a number rewrites it as a regular floating-point number, even + 0. That turns 1.50 into 1.5, and an ID above 2^53 into a different ID:
$ jq -c '{price, id}' config.json
{"price":1.50,"id":9007199254740993}
$ jq -c '.price += 0 | .id += 0 | {price, id}' config.json
{"price":1.5,"id":9007199254740992}
  • Duplicate keys are silently collapsed. The last one wins, no warning:
$ cat dup.json
{"a": 1, "a": 2}
$ jq -c . dup.json
{"a":2}
  • Comments can’t survive, because jq won’t parse the file at all (see mistake 2). For tsconfig.json, VS Code settings and other files with comments, jq is the wrong tool.

More than one file

Give jq two files and it writes both results to one output stream, so > tmp.json && mv tmp.json a.json leaves a.json with two documents in it:

$ jq -c '.b = true' a.json b.json
{"a":1,"b":true}
{"a":2,"b":true}
$ for f in a.json b.json; do jq_inplace '.b = true' "$f"; done
$ jq -c . a.json b.json
{"a":1,"b":true}
{"a":2,"b":true}

Loop over the files and write each one back on its own.

Common edits that keep the whole document

Each of these outputs the full file, so it’s safe to write back:

$ jq -c '.db.pool.max = 20 | .db' config.json
{"pool":{"max":20}}
$ jq -c '(.port, .items[].price) = 0 | [.port, .items[].price]' config.json
[0,0,0]
$ jq -c 'del(.items[] | select(.name == "a")) | .items' config.json
[{"name":"b","price":2}]
$ jq -c '.items |= map(if .name == "b" then .price += 1 else . end) | .items' config.json
[{"name":"a","price":1},{"name":"b","price":3}]

Setting a path that doesn’t exist creates it. A comma inside the parentheses sets several paths to the same value. del() takes a path, so the select() inside it picks what to delete instead of cutting the output down to the match. (The trailing | .db and | .items are only there to keep the output short; drop them when writing back.)

Why there’s no -i

jq had an in-place flag once. A jq contributor explained in 2020 that it “caused problems”: a jq program can read several files at once, so jq doesn’t know which file each result belongs to. The feature request from 2013, issue #105, is still open, and pull request #3488, which adds --in-place, was opened in February 2026 and hadn’t been merged as of 2026-09-30. None of the three builds I tested lists an in-place option in jq --help.

What I’d do

  1. Never redirect jq’s output into the file it’s reading, with > or tee.
  2. Use jq_inplace (or the same checks written out): temp file, exit code, empty stderr, non-empty output, copy back.
  3. Before writing, run the filter once without writing and check the output starts at the top of your file.
  4. Pass numbers with --argjson, and add --indent or --tab if you care about the diff.
  5. On a Mac, check jq --version. The built-in one doesn’t report parse errors in its exit code.

How to check this yourself

$ jq '.port = 9090' config.json | head -3
{
  "name": "demo",
  "port": 9090,

If the first line of output isn’t the start of your document, the filter returns a piece of it. For the exit code, run jq . settings.json; echo $? on a file with a comment or a trailing comma: the official releases print 5, the macOS build prints 0.

What this test does not cover

  • sponge from moreutils, which the FAQ also suggests. It isn’t on macOS by default and I didn’t install it.
  • Linux and Windows builds, and upstream releases older than the two in the box. The macOS build is an older upstream release with Apple’s changes, so its exit codes don’t tell you what that upstream release does.
  • Two programs writing the same file at once. The FAQ suggests flock for that; I didn’t test it.
  • Very large files, where holding a second copy in a temp file matters.

Test setup

The official jq-macos-arm64 release binaries for the two versions in the box above, SHA-256 checked against each release’s sha256sum.txt, and macOS’s /usr/bin/jq, on macOS 15.3.1, Apple Silicon, tested 2026-09-30. The commands ran in bash with umask 022.

In-place editing is covered in the jq FAQ on GitHub (https://github.com/jqlang/jq/wiki/FAQ, checked 2026-09-30), which recommends a temporary file or sponge and warns against > and tee. The FAQ doesn’t cover the empty-output, permission, symlink and fragment cases, or the macOS exit code; those come from the tests above. Options like --arg, --argjson, --indent and -a are in the official manual, https://jqlang.org/manual/.

Related: merging two JSON files by key and converting JSON to CSV.