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

Does anyone know why some of my json elements have a backslash ( \) and others not?

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

Ideally, I would like NONE to escape from them ...

This was created by redefinition as_jsonin two models. The has_many Dogs face.

#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
+3
source share
2 answers

Try uninstalling to_jsonon dogs.to_json.

+7
source

Check out jonathanjulian.com Rails to_json or as_json ?

+12
source

Source: https://habr.com/ru/post/1778363/


All Articles