【问题标题】:Rails 3: Escape characters (\) appearing in part of JSON stringRails 3:转义字符(\)出现在 JSON 字符串的一部分中
【发布时间】:2011-05-19 21:25:45
【问题描述】:

有人知道为什么我的一些 json 元素被反斜杠(\)转义,而另一些则没有?

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

理想情况下,我不希望它们中的任何一个被逃脱......

这是通过在两个模型中覆盖 as_json 生成的。人 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

【问题讨论】:

    标签: ruby-on-rails json serialization object-graph


    【解决方案1】:

    查看 jonathanjulian.com 的Rails to_json or as_json

    【讨论】:

      【解决方案2】:

      尝试删除dogs.to_json 上的to_json

      【讨论】:

      • BINGO! 谢谢!你明白为什么会这样吗?因为我不……还是太绿了。
      • 通过在狗上调用 to_json 来重新编码它,而第二个编码导致了转义。
      • 我无法完成这项工作 - 删除 to_json 会导致为每个 Dog 返回 inspect 字符串。但这种方法奏效了:stackoverflow.com/questions/4170372/…
      • @zetetic:它绝对适用于 Rails 3。你使用的是哪个版本?
      • Rails 3.0.1,Ruby 1.9.2。如果我理解正确,它应该按照你的描述工作,那就是它应该在关联上调用as_json。也许我的环境中有些东西很无聊。
      猜你喜欢
      • 1970-01-01
      • 2013-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-31
      • 1970-01-01
      相关资源
      最近更新 更多