Sorting JSON Arrays in the Terminal
Sort JSON arrays by a field, by date, in descending order, or by several keys, and sort object keys alphabetically. All with one fx command (install fx).
Many examples end with list, which prints one value per line. Most use this users.json:
[
{"name": "carol", "age": 35, "signup": "2024-03-02T09:15:00Z"},
{"name": "Alice", "age": 28, "signup": "2023-11-20T14:00:00Z"},
{"name": "bob", "age": 42, "signup": "2024-01-05T08:30:00Z"},
{"name": "Dave", "age": 28, "signup": "2024-06-18T17:45:00Z"}
]Sort a JSON Array of Numbers or Strings
The sort built-in sorts an array of strings:
echo '["pear", "apple", "Banana"]' | fx sort listBanana
apple
pearWARNING
sort compares values as strings, the way JavaScript's Array.prototype.sort does, so [10, 2, 33, 4] stays [10, 2, 33, 4]. For numbers, use sortBy(x => x) or .sort((a, b) => a - b).
echo '[10, 2, 33, 4]' | fx 'sortBy(x => x)' list2
4
10
33Sort JSON Array of Objects by Key
sortBy(fn) sorts by the value that fn returns:
fx users.json 'sortBy(x => x.age)' '@.name'[
"Alice",
"Dave",
"carol",
"bob"
]'@.name' only makes the output shorter. Leave it out to get the full objects.
Sort in Descending Order
Add reverse after sortBy:
fx users.json 'sortBy(x => x.age)' reverse '@.name' listbob
carol
Dave
AliceOr pass a comparator to JavaScript's .sort: '.sort((a, b) => b.age - a.age)'. Unlike reverse, it keeps the original order of equal ages (Alice before Dave).
Sort Strings Case-Insensitively
Plain string comparison puts uppercase letters before lowercase ones ("Alice", "Dave", "bob", "carol"). Use localeCompare to get alphabetical order:
fx users.json '.sort((a, b) => a.name.localeCompare(b.name))' '@.name' listAlice
bob
carol
DavesortBy(x => x.name.toLowerCase()) gives the same result.
Sort JSON by Date
ISO 8601 timestamps that all use the same time zone sort correctly as strings, so sortBy(x => x.signup) works. To get newest first, compare Date objects:
fx users.json '.sort((a, b) => new Date(b.signup) - new Date(a.signup))' '@.signup' list2024-06-18T17:45:00Z
2024-03-02T09:15:00Z
2024-01-05T08:30:00Z
2023-11-20T14:00:00ZParse the dates when the time zone offsets differ or the format is not ISO. Plain sort would put the +02:00 timestamp last, but it is the earliest (08:00 UTC):
echo '["2024-05-01T10:00:00+02:00", "2024-05-01T09:30:00Z", "2024-05-01T08:45:00Z"]' \
| fx 'sortBy(x => Date.parse(x))' list2024-05-01T10:00:00+02:00
2024-05-01T08:45:00Z
2024-05-01T09:30:00ZSort by Multiple Keys
Join the comparisons with ||. The next key is used only when the previous comparison returns 0, and each key can use its own direction. This sorts orders.json by status in ascending order, then by total in descending order:
fx orders.json '.sort((a, b) => a.status.localeCompare(b.status) || b.total - a.total)' \
'@`${x.status} ${x.id} ${x.total}`' listcancelled A-101 42
pending A-099 120
pending A-104 89
shipped A-102 59.9
shipped A-110 15.5Get the Top N Items
Sort, then use .slice. These are the three largest orders:
fx orders.json 'sortBy(x => -x.total)' '.slice(0, 3)' '@`${x.id} ${x.total}`' listA-099 120
A-104 89
A-102 59.9Sort JSON Object Keys Alphabetically
Turn each object into entries, sort them, and build it back with Object.fromEntries. To sort the keys at every level, run that inside walk, which applies a function to every nested value:
fx config.json 'walk(x => x && typeof x === "object" && !Array.isArray(x)
? Object.fromEntries(Object.entries(x).sort(([a], [b]) => a.localeCompare(b)))
: x)'Input:
{
"version": 2,
"services": {
"web": {"port": 8080, "image": "nginx"},
"api": {"port": 3000, "image": "node", "env": {"PORT": "3000", "DEBUG": "false"}}
},
"name": "shop"
}Output:
{
"name": "shop",
"services": {
"api": {
"env": {
"DEBUG": "false",
"PORT": "3000"
},
"image": "node",
"port": 3000
},
"web": {
"image": "nginx",
"port": 8080
}
},
"version": 2
}Arrays keep their order. Only object keys are sorted.
Sort Newline-Delimited JSON (NDJSON)
fx processes an NDJSON stream one value at a time. Without --slurp, sortBy gets a single object and fails with Error: Cannot sort object. Use -s to collect every line into one array first. To print the result as NDJSON again, turn each object into a string and print one per line with list:
cat requests.log | fx -s 'sortBy(x => x.ts)' 'map(x => JSON.stringify(x))' listInput:
{"ts": "2024-05-01T12:00:03Z", "path": "/api/cart", "ms": 212}
{"ts": "2024-05-01T12:00:01Z", "path": "/api/login", "ms": 48}
{"ts": "2024-05-01T12:00:05Z", "path": "/api/search", "ms": 931}
{"ts": "2024-05-01T12:00:02Z", "path": "/api/items", "ms": 377}Output:
{"ts":"2024-05-01T12:00:01Z","path":"/api/login","ms":48}
{"ts":"2024-05-01T12:00:02Z","path":"/api/items","ms":377}
{"ts":"2024-05-01T12:00:03Z","path":"/api/cart","ms":212}
{"ts":"2024-05-01T12:00:05Z","path":"/api/search","ms":931}