what is the best way to convert a json formatted key value pair to ruby hash with symbol as key?

前端 未结 7 846
无人共我
无人共我 2020-12-23 13:08

I am wondering what is the best way to convert a json formatted key value pair to ruby hash with symbol as key: example:

{ \'user\': { \'name\': \'foo\', \'         


        
7条回答
  •  情话喂你
    2020-12-23 13:26

    Recursive method:

    require 'json'
    
    def JSON.parse(source, opts = {})
      r = JSON.parser.new(source, opts).parse
      r = keys_to_symbol(r) if opts[:symbolize_names]
      return r
    end
    
    def keys_to_symbol(h)
      new_hash = {}
      h.each do |k,v|
        if v.class == String || v.class == Fixnum || v.class == Float
          new_hash[k.to_sym] = v
        elsif v.class == Hash
          new_hash[k.to_sym] = keys_to_symbol(v)
        elsif v.class == Array
          new_hash[k.to_sym] = keys_to_symbol_array(v)
        else
          raise ArgumentError, "Type not supported: #{v.class}"
        end
      end
      return new_hash
    end
    
    def keys_to_symbol_array(array)
      new_array = []
      array.each do |i|
        if i.class == Hash
          new_array << keys_to_symbol(i)
        elsif i.class == Array
          new_array << keys_to_symbol_array(i)
        else
          new_array << i
        end
      end
      return new_array
    end
    

提交回复
热议问题