Rails 3:JSON 字符串中出现转义字符 (\)
有人知道为什么我的一些 json 元素被反斜杠(\
) 转义,而其他元素却没有?
{"first":"John","last":"Smith","dogs":"[{\"name\":\"Rex\",\"breed\":\"Lab\"},{\"name\":\"Spot\",\"breed\":\"Dalmation\"},{\"name\":\"Fido\",\"breed\":\"Terrier\"}]"}
理想情况下,我不希望它们中的任何一个被转义...
这是通过在两个模型中重写 as_json
生成的。人有很多狗。
#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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看 jonathanjulian.com 的 Rails to_json 或 as_json?
Check out jonathanjulian.com's Rails to_json or as_json?
尝试删除
dogs.to_json
上的to_json
。Try removing the
to_json
ondogs.to_json
.