Jq: Can't work out how to sort_by

Created on 12 May 2015  路  4Comments  路  Source: stedolan/jq

Using jq-1.4, I can't work out how to sort a JSON file by .NextBus.EstimatedArrival. What am I missing from:

curl -s http://s.natalian.org/2015-05-12/sg-bus.json | jq '.Services[] | sort_by(.NextBus.EstimatedArrival)'

Which results in errors like "jq: error: Cannot index array with string".

Ideally I want to sort in place, i.e. print out the original JSON, only sorted by EstimatedArrival

support

Most helpful comment

@kaihendry - sort_by expects an array as input, but you gave it .Services[] (a stream of objects) instead.

Thus, simply remove the square brackets.

All 4 comments

@kaihendry - sort_by expects an array as input, but you gave it .Services[] (a stream of objects) instead.

Thus, simply remove the square brackets.

Ah, thank you! curl -s http://s.natalian.org/2015-05-12/sg-bus.json | jq '.Services | sort_by(.NextBus.EstimatedArrival)' does the trick. :beer:

But how do I re-incorporate the the original elements of the JSON like BusStopID of http://s.natalian.org/2015-05-12/sg-bus.json?

Use |= instead of =.

That is:

.Services |= sort_by(.NextBus.EstimatedArrival)

If effect, this says: copy the object but update the .Services value.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sloanlance picture sloanlance  路  3Comments

rubensayshi picture rubensayshi  路  3Comments

thedward picture thedward  路  3Comments

lhunath picture lhunath  路  3Comments

ve3ied picture ve3ied  路  4Comments