Rails return JSON serialized attribute with_indifferent_access

前端 未结 4 1437
日久生厌
日久生厌 2021-02-07 05:55

I previously had:

serialize :params, JSON

But this would return the JSON and convert hash key symbols to strings. I want to reference the hash

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-07 06:53

    I ended up using a variation on bimsapi's solution that you can use not only with simple un-nested JSON but any JSON.

    Once this is loaded...

    module JsonHelper
    
      class JsonWithIndifferentAccess
        def self.load(str)
          self.indifferent_access JSON.load(str)
        end
    
        def self.dump(obj)
          JSON.dump(obj)
        end
    
        private
    
          def self.indifferent_access(obj)
            if obj.is_a? Array
              obj.map!{|o| self.indifferent_access(o)}
            elsif obj.is_a? Hash
              obj.with_indifferent_access
            else
              obj
            end
          end
      end
    
    end
    

    then instead of calling

    JSON.load(http_response)
    

    you just call

    JsonHelper::JsonWithIndifferentAccess.load(http_response)
    

    Does the same thing but all the nested hashes are indifferent access.

    Should serve you well but think a little before making it your default approach for all parsing as massive JSON payloads will add significant ruby operations on top of the native JSON parser which is optimised in C and more fully designed for performance.

提交回复
热议问题