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

前端 未结 7 798
无人共我
无人共我 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:37

    There isn't anything built in to do the trick, but it's not too hard to write the code to do it using the JSON gem. There is a symbolize_keys method built into Rails if you're using that, but that doesn't symbolize keys recursively like you need.

    require 'json'
    
    def json_to_sym_hash(json)
      json.gsub!('\'', '"')
      parsed = JSON.parse(json)
      symbolize_keys(parsed)
    end
    
    def symbolize_keys(hash)
      hash.inject({}){|new_hash, key_value|
        key, value = key_value
        value = symbolize_keys(value) if value.is_a?(Hash)
        new_hash[key.to_sym] = value
        new_hash
      }
    end
    

    As Leventix said, the JSON gem only handles double quoted strings (which is technically correct - JSON should be formatted with double quotes). This bit of code will clean that up before trying to parse it.

提交回复
热议问题