Sorting JSON in place by a value

Published: Tuesday, May 12, 2015 Last modified: Sunday, Jun 9, 2024

Lets take a REAL WORLD example of JSON file and lets have the typical case of sorting it by a particular value in its array. The next bus’s EstimatedArrival !

Use case: We want to find the next bus! Answer is 61 btw. :)

jq / shell

curl -s |
jq '.Services |= sort_by(.NextBus.EstimatedArrival)'


Slightly more compressed version:


TODO: gaqzi sez something like python -c "import json ; import sys; import dateutil; print sorted(json.load(sys.stdin)['Services'], key=lambda x: int(dateutil.parse(x['NextBus']['EstimatedArrival'])))" but evidently the dateutil library in Python sucks, so comparing the iso8601 dates is actually non-trivial.

Golang by Zoltan Giber.


First example I have where I managed to output the same values as the original, just sorted aka “in place”:


$jf = file_get_contents("");

$j =json_decode($jf);

function my_sort($a, $b) {
	if ($a->NextBus->EstimatedArrival < $b->NextBus->EstimatedArrival) {
		return -1;
	} else if ($a->NextBus->EstimatedArrival > $b->NextBus->EstimatedArrival) {
		return 1;
	} else {
		return 0;

usort($j->Services, 'my_sort');
echo json_encode($j, JSON_PRETTY_PRINT);