Skip to content

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:

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:

bash
echo '["pear", "apple", "Banana"]' | fx sort list
Banana
apple
pear

WARNING

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

bash
echo '[10, 2, 33, 4]' | fx 'sortBy(x => x)' list
2
4
10
33

Sort JSON Array of Objects by Key ​

sortBy(fn) sorts by the value that fn returns:

bash
fx users.json 'sortBy(x => x.age)' '@.name'
json
[
  "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:

bash
fx users.json 'sortBy(x => x.age)' reverse '@.name' list
bob
carol
Dave
Alice

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

bash
fx users.json '.sort((a, b) => a.name.localeCompare(b.name))' '@.name' list
Alice
bob
carol
Dave

sortBy(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:

bash
fx users.json '.sort((a, b) => new Date(b.signup) - new Date(a.signup))' '@.signup' list
2024-06-18T17:45:00Z
2024-03-02T09:15:00Z
2024-01-05T08:30:00Z
2023-11-20T14:00:00Z

Parse 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):

bash
echo '["2024-05-01T10:00:00+02:00", "2024-05-01T09:30:00Z", "2024-05-01T08:45:00Z"]' \
  | fx 'sortBy(x => Date.parse(x))' list
2024-05-01T10:00:00+02:00
2024-05-01T08:45:00Z
2024-05-01T09:30:00Z

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

bash
fx orders.json '.sort((a, b) => a.status.localeCompare(b.status) || b.total - a.total)' \
  '@`${x.status} ${x.id} ${x.total}`' list
cancelled A-101 42
pending A-099 120
pending A-104 89
shipped A-102 59.9
shipped A-110 15.5

Get the Top N Items ​

Sort, then use .slice. These are the three largest orders:

bash
fx orders.json 'sortBy(x => -x.total)' '.slice(0, 3)' '@`${x.id} ${x.total}`' list
A-099 120
A-104 89
A-102 59.9

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

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

json
{
  "version": 2,
  "services": {
    "web": {"port": 8080, "image": "nginx"},
    "api": {"port": 3000, "image": "node", "env": {"PORT": "3000", "DEBUG": "false"}}
  },
  "name": "shop"
}

Output:

json
{
  "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:

bash
cat requests.log | fx -s 'sortBy(x => x.ts)' 'map(x => JSON.stringify(x))' list

Input:

{"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}

See Also ​