Rails 3: Escape characters (\) appearing in part of JSON string

风格不统一 提交于 2020-01-04 02:30:55

问题


Anyone know why some of my json elements are being backslash(\) escaped while others are not?

{"first":"John","last":"Smith","dogs":"[{\"name\":\"Rex\",\"breed\":\"Lab\"},{\"name\":\"Spot\",\"breed\":\"Dalmation\"},{\"name\":\"Fido\",\"breed\":\"Terrier\"}]"}

Ideally I'd like NONE of them to be escaped...

This was generated by overriding as_json in two models. Person has_many Dogs.

#models/person.rb
class Person < ActiveRecord::Base
  has_many :dogs

  def as_json(options={}) 
     {
       :first => first,
       :last => last,
       :dogs => dogs.to_json
     }
   end
end

#models/dog.rb
class Dog < ActiveRecord::Base
  belongs_to :people

  def as_json(options={})
    {
      :name => name, 
      :breed => breed
    }
  end
end

回答1:


Try removing the to_json on dogs.to_json.




回答2:


Check out jonathanjulian.com's Rails to_json or as_json?



来源:https://stackoverflow.com/questions/4348223/rails-3-escape-characters-appearing-in-part-of-json-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!