Gaurav Bose
Gaurav Bose

Reputation: 25

JQ sort integer values in JSON

I have a bunch of JSON objects as:

{"AccountID":"290859614811","number_of_requests":"59944"}
{"AccountID":"421258792169","number_of_requests":"3132"}
{"AccountID":"433594311540","number_of_requests":"1541"}
{"AccountID":"406912498377","number_of_requests":"678"}
{"AccountID":"850981987534","number_of_requests":"558"}
{"AccountID":"763725063017","number_of_requests":"470"}
{"AccountID":"notaccount","number_of_requests":"8"}
....

I am trying to sort them in ascending order based on the number_of_requests.

but when I run the following:

jq -S '.results[] | map( { (.field) : .value} ) | add ' FILENAME | jq -s -c 'sort_by(.number_of_requests)[]'

I end up with:

{"AccountID":"433594311540","number_of_requests":"1541"}
{"AccountID":"421258792169","number_of_requests":"3132"}
{"AccountID":"763725063017","number_of_requests":"470"}
{"AccountID":"850981987534","number_of_requests":"558"}
{"AccountID":"290859614811","number_of_requests":"59944"}
{"AccountID":"406912498377","number_of_requests":"678"}
{"AccountID":"notaccount","number_of_requests":"8"}
...

Basically, the sort_by function treats "558"/"59944" as lesser than "8" , "6" etc. Is there a way to work around this?

Upvotes: 1

Views: 3780

Answers (1)

rici
rici

Reputation: 241771

You need to convert the value to a number, with tonumber:

jq -s -c 'sort_by(.number_of_requests|tonumber)'

Upvotes: 9

Related Questions