I am wondering what is the best way to convert a json formated key value pair to ruby hash with symbol as key : examole:
{ 'user': { 'name': 'foo', 'age': 40, 'location': { 'city' : 'bar', 'state': 'ca' } } }
==>
{ :user=>{ :name => 'foo', :age =>'40', :location=>{ :city => 'bar', :state=>'ca' } } }
Is there a helper method can do this?
From stackoverflow
-
Of course, there is a json gem, but that handles only double quotes.
edavey : As madlep says below - that's all you need if you know that the JSON will be valid (e.g. you're making it yourself!)Justin L. : This doesn't work. `JSON.parse(JSON.generate([:a])) # => ["a"]`Leventix : That's because JSON can't represent symbols. You can use: `Marshal.load(Marshal.dump([:a]))` instead. -
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_keysmethod 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 } endAs 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.
0 comments:
Post a Comment