rob*_*nex 34 json ruby-on-rails
我已经完成了这一千次,但我仍然不熟悉render :json手柄弦如何.
要设置范围,我们来谈谈Rails 3
这就是它现在的行为方式:
...
render :json => 'This is the string'
...
Run Code Online (Sandbox Code Playgroud)
将返回浏览器:
This is the string
Run Code Online (Sandbox Code Playgroud)
这实际上不是有效的JSON响应:S
理想情况下它应该呈现这样的东西:
"This is the string"
Run Code Online (Sandbox Code Playgroud)
铁轨指南甚至说:
您不需要在要渲染的对象上调用to_json.如果使用:json选项,render将自动为您调用to_json.
并且调用"This is the string".to_json实际上正在"\"This is the string\""按预期返回.
"This is the string".to_json #=> "\"This is the string\""
Run Code Online (Sandbox Code Playgroud)
我错了吗?
Mat*_*chu 54
我同意这首先是意外的行为,但实际上它有一些很好的意义.
例如,考虑一下您期望这样做:
output = {'foo' => 'bar'}.to_json
render :json => output
Run Code Online (Sandbox Code Playgroud)
即使to_json有点多余,你也期望得到结果{foo: "bar"}.但请注意,结果{'foo' => 'bar'}.to_json实际上是一个字符串.所以,上面的代码块相当于:
render :json => '{foo: "bar"}'
Run Code Online (Sandbox Code Playgroud)
如果render传递给JSON编码字符串:json,你会得到"{foo: \"bar\"}",这绝对不是预期的行为.
所以这是交易:render检查:json参数是否是一个字符串.如果是这样,它假定它是一个JSON字符串,你已经运行to_json,并传递字符串.如果没有,它将to_json在对象上运行.
我认为文档应该澄清一下,但是你有它.虽然乍一看并不完全直观,但如果它以任何其他方式工作,我会感到惊讶.