JSON encoding wrongly escaped (Rails 3, Ruby 1.9.2)

后端 未结 7 1495
醉梦人生
醉梦人生 2020-12-01 08:14

In my controller, the following works (prints \"oké\")

puts obj.inspect

But this doesn\'t (renders \"ok\\u00e9\")

render :j         


        
7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-01 08:49

    render :json will call .to_json on the object if it's not a string. You can avoid this problem by doing:

    render :json => JSON.generate(obj)
    

    This will by pass a string directly and therefore avoid the call to ActiveSupport's to_json.

    Another approach would be to override to_json on the object you are serializing, so in that case, you could do something like:

    class Foo < ActiveRecord::Base
      def to_json(options = {})
        JSON.generate(as_json)
      end
    end
    

    And if you use ActiveModelSerializers, you can solve this problem by overriding to_json in your serializer:

    # controller
    respond_with foo, :serializer => MySerializer
    
    # serializer
    attributes :bar, :baz
    
    def to_json(options = {})
      JSON.generate(serializable_hash)
    end
    

提交回复
热议问题