mercredi 17 juin 2015

Converting a ruby structure to a hash

I've got a bit of a headache here - I'm pretty new to Ruby...

I've got a structure like so returned from Savon...

{
  :item => [{
              :key =>  "result",
              :value=> "success"
            },
            {
              :key =>  "data",
              :value=> {
                  :item => [{ :key => "displayName", 
                              :value => "Matt" 
                            },
                            {
                              :key => "messages",
                              :value => { 
                                  :items => [{....}]
                            }
                       ]
               }
       }]
}

And I need to get it to be like...

{
  :result => success
  :data => [{
              :displayName => "Matt"
           },
           {
              :messages => [{
                              :messageName => "Test Message"
                           }]
           }]
}

So I can easily manipulate and navigate the data structure I've tried a few methods including just passing the value of :item ...

def convertData(data)
  result = {}
  if(data!=nil)
    data.each do |item|
      key = item[:key] 
      value = item[:value] 
      if(value.instance_of?(Hash))
        result[key] = convertData(value[:item])
      else
        result[key] = value
      end  
    end
  end
  return result
end

But this just gives me a tonne of Type errors for symbol to integer conversion (I assume that's the array index playing up). Any help much appreciated.




Aucun commentaire:

Enregistrer un commentaire