Rails 3: Escape characters (\) appearing in part o

2019-07-01 13:59发布

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

2条回答
可以哭但决不认输i
2楼-- · 2019-07-01 14:22

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

查看更多
时光不老,我们不散
3楼-- · 2019-07-01 14:28

Try removing the to_json on dogs.to_json.

查看更多
登录 后发表回答