Sorting JSON in place by a value

Published: Tuesday, May 12, 2015 Last modified: Thursday, Nov 14, 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 http://s.natalian.org/2015-05-12/sg-bus.json |
jq '.Services |= sort_by(.NextBus.EstimatedArrival)'

Javascript

https://jsfiddle.net/kaihendry/efctamcx/1/

Slightly more compressed version: http://codepen.io/ponyfleisch/pen/BNKrvP?editors=001

Python

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

https://play.golang.org/p/nRqOm0-TMn by Zoltan Giber.

PHP

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

<?php

$jf = file_get_contents("http://s.natalian.org/2015-05-12/sg-bus.json");

$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);

?>