Sorting JSON data in Ruby
<p>I have following JSON structure:</p>

<pre><code> {
  "name": "MessageEnvelope",
  "type": "record",
  "fields": [
   {
      "name": "message",
      "type": 
        {
          "name": "Message",
          "type": "record",
           "fields": [
             ....
            ]
        }
   },
   {
      "name": "pipeline_system",
      "type": {
                 "type": "enum",
                 "name": "PipelineSystem",
                 "symbols": [ "enterprise", "backscoring", "compliance" ]
              }
    },
    {
      "name": "batch_id",
      "type": [ "null", "string" ]
    }
 ]
}
</code></pre>

<p>I am looking to sort the above JSON file as best as it could be. For example:</p>

<pre><code>fields : [
  {
      "name": "batch_id",
      "type": [ "null", "string" ]
    }, 
  ...
  ...
  {
      "name": "pipeline_system",
      "type": {
                 "type": "enum",
                 "name": "PipelineSystem",
                 "symbols": [ "backscoring",  "compliance", "enterprise" ]
              }
    } 
</code></pre>

<p>Like it sorts the internal arrays as well as hashes. I am trying to write following:</p>

<pre><code>def sort(collection)
   if collection.is_a?(Hash)
    puts "Hash Object...."
    if(collection["type"]=="record")
      puts "record found...     Type = #{collection["fields"].class}";
      if collection["fields"].is_a?(Array)
        puts "fields type is array...."           #we can sort fields arrays on the basis of name
        collection["fields"].sort_by{|arrayCollectionElement| arrayCollectionElement["name"] } 
        arrayCollection = collection["fields"]    #this is array of hash...we can sort them on the basis of name..done above in sort by...
        puts "class  = #{arrayCollection.class}"
        puts "sorted fields:  #{arrayCollection}"
      end
    end   #else it is again a hash
  end
  collection
end
</code></pre>

<p>but it is not sorting the fields array on the basis of names. </p>

<p>Appreciate any possible help!</p>