Search code examples
jsonpojo

How to check if JSON response fields are alphabetically sorted?


How to validate the JSON Response fields? After validating the fields I need to check whether the fields are alphabetically sorted or not. How would I do it ?


Solution

  • The JSON object is unordered set of name/value pairs. There is no guarangee of ordering at all. You need to take json object keys list and sort them. After sorting access to object fields by sorted keys list.

    If you mean how to check list (array) of values. You need to implement simple loop through array and check that each element must be less than next element in sorting comparision criteria.

    For js language checking array for alpha ordering may be done like this:

    var array = ["Apple", "Application", "AppName", "Happy"];
    
    var isSortedAlpha = array.reduce(function(res, current, index, arr) {
      return res && arr[index&&index-1] <= current
    }, true);