Search code examples
jsonsortingparsingjqjsonlines

Validate JSON fields sort order


I have the following JSON records stored in a container

{"memberId":123,"memberCity":"Chicago","lastTransaction":1504155600000}
{"memberId":123,"memberCity":"Chigago","lastTransaction":150175600000}
{"memberId":123,"memberCity":"New York","lastTransaction":150195600000}

I am looking to validate that the sort order in which these records are stored are sorted by memberId ASC, memberCity ASC, lastTransaction ASC

Is there a way via jq that I can assert (true/false) the sort order, taking multiple fields into account?


Solution

  • Any solution that requires using the -s command-line option has the drawback of requiring more memory than is needed. Similarly using sort is inadvisable in general, but if one wants a concise and simple solution, one could go with:

    jq -s 'map([.memberId, .memberCity, .lastTransaction]) | . == sort' 
    

    or even in the specific case given:

    jq -s 'map(.[]) | . == sort'