Editing JSON Files In Place
Change a value in a JSON file from bash without opening an editor. Every fx argument is a JavaScript expression, so an edit is a normal JS assignment. Install fx first.
Examples use this config.json:
{
"name": "billing-api",
"version": "1.4.2",
"port": 8080,
"debug": true,
"database": {
"host": "db.internal",
"port": 5432
},
"tags": ["payments", "internal", "legacy"]
}Every command below prints the edited JSON. See Save Changes Back to the File to write it back.
Update a Value in a JSON File
Use the spread operator to copy the object and override one key:
fx config.json '{...x, port: 9090}'Or assign the value and return x with the comma operator:
fx config.json '.port = 9090, x'Both print the full document with "port": 9090. The assignment form is shorter for nested paths.
Set a Nested Value in JSON
Assign straight to the path:
fx config.json '.database.host = "db.prod.internal", x' .database{
"host": "db.prod.internal",
"port": 5432
}The trailing .database only narrows the printed output. Leave it out to get the whole file.
Assigning under a missing key, such as '.cache.ttl = 300, x', fails with TypeError: Cannot convert undefined or null to object. Create each parent with ??=. It assigns only when the key is missing and returns the existing or new object:
fx config.json '((x.monitoring ??= {}).alerts ??= {}).email = "oncall@example.com", x' .monitoring{
"alerts": {
"email": "oncall@example.com"
}
}Append to or Remove From a JSON Array
push adds to the end (unshift adds to the start):
fx config.json '.tags.push("v2"), x' .tags[
"payments",
"internal",
"legacy",
"v2"
]Remove by value with filter, or by index with splice(index, count):
fx config.json '.tags = x.tags.filter(t => t !== "legacy"), x' .tags
fx config.json '.tags.splice(1, 1), x' .tagsThe first leaves payments and internal. The second leaves payments and legacy. On a top-level array, use the ? filter shorthand: fx users.json '?.id !== 2'.
Update an Object in a JSON Array by ID
users.json holds an array of user records. Find the record, then assign to it:
fx users.json '.find(u => u.id === 2).role = "editor", x'[
{ "id": 1, "name": "Alice", "role": "admin", "active": true },
{ "id": 2, "name": "Bob", "role": "editor", "active": false },
{ "id": 3, "name": "Carol", "role": "editor", "active": true }
]To change every record, map with spread: fx users.json '@{...x, active: true}'.
Delete a Key From a JSON File
delete works at any depth. This leaves only "host" in database:
fx config.json 'delete x.database.port, x'To drop several keys at once, destructure them away. This leaves name, port, database, and tags:
fx config.json '({debug, version, ...rest}) => rest'To rename a key, copy it and then delete the old one: 'x.service = x.name, delete x.name, x'. The new key goes to the end of the object. For more on this, see Renaming and Restructuring JSON Keys.
Save Changes Back to the File
Add the save function as the last argument. It writes the result to the input file with 2-space indentation and also prints it:
fx config.json '.port = 9090, x' savesave needs a file name as the first argument. With piped input there is nothing to write back to:
cat config.json | fx '.port = 9090, x' save .port = 9090, x save
^^^^
GoError: specify a file as the first argument to be able to save: fx file.jsonsave writes to a temporary file and renames it over the original, so a failed run never leaves a half-written file, and the file keeps its permissions. It refuses to write through a symlink, and it only works on files that contain a single JSON value; on a JSON Lines file it fails with save supports a single JSON value, but events.jsonl contains several.
To write the result somewhere else instead, redirect it:
fx config.json '.port = 9090, x' > config.prod.jsonNever redirect to the file you are reading (> config.json). The shell empties the file before fx reads it. Use save for that.
WARNING
fx accepts JSON with comments and trailing commas, but it writes plain JSON. Comments in files like tsconfig.json are lost after save or a redirect.
Pass Shell Variables Into an fx Expression
For numbers you trust, put the whole expression in double quotes:
PORT=9090
fx config.json ".port = $PORT, x"Don't wrap strings in quotes yourself. A value that contains a quote breaks the expression:
NAME='Bob "The Builder"'
fx users.json ".[1].name = \"$NAME\", x" .[1].name = "Bob "The Builder"", x
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
x[1].name = "Bob "The Builder"", x
Unexpected identifierEncode the value as a JSON string first. The output is a valid JS string literal:
NAME='Bob "The Builder" O'\''Neil'
NAME_JSON=$(printf '%s' "$NAME" | fx -r 'JSON.stringify(x)')
fx users.json ".[1].name = $NAME_JSON, x" '.[1]'{
"id": 2,
"name": "Bob \"The Builder\" O'Neil",
"role": "viewer",
"active": false
}Edit Multiple JSON Files With a Shell Loop
Run save for each file:
for f in services/*.json; do
fx "$f" '.debug = false, x' save > /dev/null
done
grep -H '"debug"' services/*.jsonservices/auth.json: "debug": false,
services/billing.json: "debug": false,
services/search.json: "debug": false,