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

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

    The most convenient way is by using the nice_hash gem: https://github.com/MarioRuiz/nice_hash

    require 'nice_hash'
    my_str = "{ 'user': { 'name': 'foo', 'age': 40, 'location': { 'city' : 'bar', 'state': 'ca' } } }"
    
    # on my_hash will have the json as a hash
    my_hash = my_str.json
    
    # or you can filter and get what you want
    vals = my_str.json(:age, :city)
    
    # even you can access the keys like this:
    puts my_hash._user._location._city
    puts my_hash.user.location.city
    puts my_hash[:user][:location][:city]
    

提交回复
热议问题