4

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
Meltemi
  • 37,979
  • 50
  • 195
  • 293

2 Answers2

12

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

Stu Thompson
  • 38,370
  • 19
  • 110
  • 156
Samo
  • 8,202
  • 13
  • 58
  • 95
7

Try removing the to_json on dogs.to_json.

rwilliams
  • 21,188
  • 6
  • 49
  • 55
  • **BINGO!** Thanks! You understand why that happened? cuz I don't...still too green. – Meltemi Dec 03 '10 at 17:46
  • 2
    By calling to_json on dogs you were re-encoding it and the second encoding caused the escaping. – rwilliams Dec 03 '10 at 18:38
  • I couldn't make this work -- removing `to_json` resulted in the `inspect` string being returned for each `Dog`. But this approach worked: http://stackoverflow.com/questions/4170372/serializing-and-deserializing-complex-rails-objects-with-json/4170710#4170710 – zetetic Dec 03 '10 at 20:47
  • 1
    @zetetic: It definitely works for Rails 3. Is that what version you're using? – rwilliams Dec 03 '10 at 22:05
  • Rails 3.0.1, Ruby 1.9.2. If I understand correctly it *ought* to work as you describe, that is it should call `as_json` on the associations. Maybe something is borked in my environment. – zetetic Dec 03 '10 at 22:16
  • @zetetic: Yeah, I'm not really sure what to tell you, but I just tested it on my Rails 3 app and it worked perfectly respecting the as_json definitions of both models. – rwilliams Dec 03 '10 at 22:20