Skip to content

Advanced Usage

Pretty print JSON without starting the interactive mode:

sh
echo '{"name": "world"}' | fx .

Syntactic Sugar

Mapping

Use @ to map. Prefix your expression with @ and fx will run it for each item.

sh
fx example.json @.title

This is the short form of:

sh
fx example.json '.map(x => x.title)'

You can also use functions with @ symbol.

sh
fx example.json @keys

TIP

Fx also supports .[] syntax. The [] operator is shorthand for .flatMap(x => x).

sh
fx example.json '.[].issues[].title'

This is the short form of:

sh
fx example.json '.flatMap(x => x.issues.flatMap(x => x.title))

Filtering

Use ? to filter. Prefix your expression with ? and fx will filter the array.

sh
fx example.json '?.size_bytes >= 1024'

This is the short form of:

sh
fx example.json '.filter(x => x.size_bytes >= 1024)'

Edit-in-place

Use the spread operator to modify the input:

sh
echo '{"count": 1}' | fx '{...x, count: x.count + 1}'

Or to modify nested objects, use the comma (,) operator:

sh
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:

sh
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 the n suffix:

sh
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.

sh
echo '{"count": Infinity}' | fx '.count + 1'

Output: Infinity

TIP

Use the --strict flag to throw an error on invalid JSON.

sh
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:

sh
ls | fx -r '[x, x.includes(".md")]'

Combine --raw and --slurp (or -rs) to process as a single string array:

sh
ls | fx -rs '.filter(x => x.includes(".md"))'

Use the skip symbol to skip printing certain results:

sh
ls | fx -r '.includes(".md") ? this : skip'

Use the list function to print an array as a list:

sh
ls | fx -rs '.filter(x => x.includes(".md"))' list

.fxrc.js

fx can recognize the .fxrc.js file, either in the current directory, the home directory, or the XDG config directory.

Here's how you can define custom functions:

js
function addOne(x) {
    return x + 1
}

Invoke your custom function in fx:

sh
echo '1' | fx addOne