Advanced Usage
Pretty print JSON without starting the interactive mode:
echo '{"name": "world"}' | fx .
Syntactic Sugar
Mapping is a frequently used process. To perform mapping, you can use the following command
curl https://fx.wtf/example.json | fx '.issues.map(x => x.title)'
Or you can use the syntactic sugar:
curl https://fx.wtf/example.json | fx '.issues[].title'
The []
operator is a shorthand for .flatMap(x => x)
.
It is useful when you need to flatten the array:
curl https://fx.wtf/example.json | fx '.issues[].labels[].length'
TIP
Fx also provides even shorter syntax for mapping:
curl https://fx.wtf/example.json | fx .issues @.title
The @
operator is a shorthand for .map(x => x)
. One benefit of using @
instead of .[]
is that @
character does not require quotes in bash/zsh.
Edit-in-place
Use spread operator to modify the input:
echo '{"count": 1}' | fx '{...x, count: x.count + 1}'
Or to modify nested objects, use comma ,
operator:
fx example.json '.owner.login = "me", x'
INFO
The ,
operator is a JavaScript feature that evaluates each of its operands (from left to right) and returns the value of the last operand.
Use the save function to save the modified input:
fx example.json 'x.name = x.name.toUpperCase(), x' save
Now the edited data will be saved to the same example.json
file.
Big Integers
If a number is bigger than 253 – 1 (max safe integer in JS), fx will parse it as BigInt. To work with BigInts in JavaScript, use n
suffix:
echo '{"count": 1234567890987654321}' | fx '.count + 1n'
Infinity and NaN
fx will parse Infinity
and NaN
as is. Those values are not valid JSON, but they are valid values in JavaScript. Supported values are Infinity
-Infinity
INF
, -INF
NaN
nan
.
echo '{"count": Infinity}' | fx '.count + 1'
Output: Infinity
TIP
Use --strict
flag to throw an error on invalid JSON.
echo '{"count": Infinity}' | fx --strict
Output:
Unexpected character 'I' on line 1.
{"count": Infinity}
..........^
Non-JSON Data
For non-JSON content, use the --raw
or -r
flag:
ls | fx -r '[x, x.includes(".md")]'
Combine --raw
and --slurp
(or -rs
) to process as a single string array:
ls | fx -rs '.filter(x => x.includes(".md"))'
Use the skip symbol to skip printing certain results:
ls | fx -r '.includes(".md") ? this : skip'
Use the list function to print array as a list:
ls | fx -rs '.filter(x => x.includes(".md"))' list
.fxrc.js
fx can recognize the .fxrc.js
file, either in the current directory, home directory, or XDG config directory.
Here's how you can define custom functions:
function addOne(x) {
return x + 1
}
Invoke your custom function in fx:
echo '1' | fx addOne