Skip to content

Filtering JSON Arrays by Condition ​

Select only the objects you need from a JSON array: by field value, text match, number range, date, or nested data. fx uses plain JavaScript conditions, so it works as a jq 'select(...)' alternative. Install fx first.

Most examples use this users.json:

json
[
  {"id": 1, "name": "Alice", "email": "alice@example.com", "status": "active", "role": "admin", "age": 34, "createdAt": "2023-11-02"},
  {"id": 2, "name": "Bob", "email": "bob@corp.io", "status": "inactive", "role": "user", "age": 27, "createdAt": "2024-02-14"},
  {"id": 3, "name": "Carol", "email": "carol@example.com", "status": "active", "role": "user", "age": 41, "createdAt": "2024-05-30"},
  {"id": 4, "name": "Dave", "email": "dave@corp.io", "status": "active", "role": "user", "age": 19, "createdAt": "2024-08-09"}
]

Select Objects Where a Field Equals a Value ​

Start the expression with ? to filter. ?.status == "active" is short for .filter(x => x.status == "active"):

bash
fx users.json '?.status == "active"' '@.name'

Output:

json
[
  "Alice",
  "Carol",
  "Dave"
]

@.name maps the result to names. '.filter(x => x.status == "active")' and the built-in 'filter(x => x.status == "active")' give the same result.

Filter with Multiple Conditions (AND, OR, NOT) ​

Use &&, ||, and parentheses. Only the leading . is sugar; refer to the element as x everywhere else:

bash
fx users.json '?.status == "active" && (x.role == "admin" || x.age < 21)' '@.name'
json
[
  "Alice",
  "Dave"
]

To negate a whole condition, use ?! followed by the expression: '?!x.email.endsWith("@example.com")' returns Bob and Dave. For a single field, '?.status != "active"' is simpler.

Filter JSON by String Contains, Starts With, or Regex ​

Any JavaScript string method works:

bash
fx users.json '?.email.includes("corp")' '@.email'
json
[
  "bob@corp.io",
  "dave@corp.io"
]

startsWith and endsWith work the same way. For a regex, call .test() on a regex literal. The i flag makes it case-insensitive:

bash
fx users.json '?/^[a-c]/i.test(x.name)' '@.name'
json
[
  "Alice",
  "Bob",
  "Carol"
]

Filter by Number Range or Date ​

Compare numbers directly: '?.age >= 25 && x.age <= 40' returns Alice and Bob. For dates, parse them with new Date():

bash
fx users.json '?new Date(x.createdAt) > new Date("2024-01-01")' '@.name'
json
[
  "Bob",
  "Carol",
  "Dave"
]

ISO 8601 dates in the same format also compare correctly as strings: '?.createdAt >= "2024-01-01" && x.createdAt < "2024-07-01"' returns Bob and Carol.

Filter Objects by Values in a Nested Array ​

Use some (at least one element matches) or every (all elements match) on the inner array. Given orders.json:

json
[
  {"id": "A-100", "total": 42.5, "items": [{"sku": "BOOK", "qty": 1}, {"sku": "PEN", "qty": 3}]},
  {"id": "A-101", "total": 310, "items": [{"sku": "LAPTOP-BAG", "qty": 1}]},
  {"id": "A-102", "total": 15, "items": [{"sku": "PEN", "qty": 5}]}
]

Find orders that contain a pen:

bash
fx orders.json '?.items.some(i => i.sku == "PEN")' '@.id'
json
[
  "A-100",
  "A-102"
]

'?.items.every(i => i.qty == 1)' returns only A-101, the order whose items all have quantity 1.

Filter Keys of a JSON Object ​

? and .filter() work on arrays. For an object, convert it to entries, filter, and convert back. Given config.json:

json
{"host": "db.local", "port": 5432, "user": "app", "password": null, "sslmode": "", "replicas": [], "timeout": 30}

Keep only numeric values:

bash
fx config.json 'x => Object.fromEntries(Object.entries(x).filter(([k, v]) => typeof v == "number"))'
json
{
  "port": 5432,
  "timeout": 30
}

Filter on the key instead with ([k]) => k.startsWith("p"). To drop specific keys, see Renaming and Restructuring JSON Keys.

Remove Null and Empty Values from JSON ​

In an array, '?x != null && x !== ""' drops null, undefined, and empty strings: [1, null, 2, "", 3] becomes [1, 2, 3]. In an object, remove null, "", and [] values with the entries pattern:

bash
fx config.json 'x => Object.fromEntries(Object.entries(x).filter(([k, v]) =>
  v != null && v !== "" && !(Array.isArray(v) && v.length == 0)))'
json
{
  "host": "db.local",
  "port": 5432,
  "user": "app",
  "timeout": 30
}

Filter, Map, and Count in One Command ​

Each argument is applied in turn to the previous result. Add len to count matches:

bash
fx users.json '?.status == "active"' len
3

Map before counting to get a different measure, for example unique roles among active users:

bash
fx users.json '?.status == "active"' '@.role' uniq len
2

Add list after '@.email' to print one match per line for other shell tools.

Filter Newline-Delimited JSON Without --slurp ​

fx processes NDJSON one value at a time, so there is no array to filter. Return the value to keep it, or skip to print nothing. Given app.log:

{"ts": "2024-06-01T10:00:01Z", "level": "info", "msg": "server started", "ms": 12}
{"ts": "2024-06-01T10:00:05Z", "level": "error", "msg": "db timeout", "ms": 5003}
{"ts": "2024-06-01T10:00:09Z", "level": "info", "msg": "GET /health", "ms": 3}
{"ts": "2024-06-01T10:00:12Z", "level": "warn", "msg": "slow query", "ms": 1840}
bash
cat app.log | fx '.ms > 1000 ? x : skip' '.msg'
db timeout
slow query

This works on endless streams like tail -f app.log, because nothing is buffered. When a value is a single object rather than an array, ?.ms > 1000 does the same thing: it keeps the value or skips it.

To count matches you need the whole stream, so use --slurp to collect it into an array first:

bash
cat app.log | fx --slurp '?.level != "info"' len
2

See Also ​