渲染:json => “在这里串"的预期结果 [英] render :json => 'string here' expected result
问题描述
我已经做过一千遍了,但是我对render :json
处理字符串的方式仍然不满意.
I have done this a thousand times but I'm still not comfortable with how the render :json
handles strings.
要设置范围,让我们来谈谈Rails 3
To set a scope let's talk about Rails 3
这是现在的行为:
...
render :json => 'This is the string'
...
将返回浏览器:
This is the string
那实际上不是有效的JSON响应:S
That's actually not a valid JSON response :S
理想情况下,它应该呈现如下内容:
Ideally it should be rendering something like this:
"This is the string"
即使导轨向导说:
您不需要在要呈现的对象上调用to_json. 如果使用:json选项,render将自动调用to_json 为你.
You don’t need to call to_json on the object that you want to render. If you use the :json option, render will automatically call to_json for you.
然后调用"This is the string".to_json
实际上会按预期返回"\"This is the string\""
.
And calling "This is the string".to_json
is actually returning "\"This is the string\""
as expected.
"This is the string".to_json #=> "\"This is the string\""
我错了吗?
推荐答案
我同意一开始这是意外行为,但实际上有一定道理.
I agree that this is unexpected behavior at first, but it actually makes some good sense.
例如,考虑一下您希望这样做:
Consider, for example, what you would expect this to do:
output = {'foo' => 'bar'}.to_json
render :json => output
即使to_json
有点多余,您也希望结果为{foo: "bar"}
.但是,请注意,{'foo' => 'bar'}.to_json
的结果实际上是一个字符串.因此,以上代码块等效于:
Even though the to_json
is kinda redundant, you expect the result to be {foo: "bar"}
. However, note that the result of {'foo' => 'bar'}.to_json
is actually a string. So, the above code block is equivalent to:
render :json => '{foo: "bar"}'
如果render
对传递给:json
的字符串进行JSON编码,则将得到"{foo: \"bar\"}"
,这肯定是不是预期的行为.
If render
were to JSON-encode strings passed to :json
, you would get "{foo: \"bar\"}"
, which is definitely not expected behavior.
这就是问题所在:render
检查:json
参数是否为字符串.如果是这样,则假定它是JSON字符串,并且您已经运行了to_json
,并将字符串传递.如果不是,它将在对象上运行to_json
.
So here's the deal: render
checks to see if the :json
argument is a string. If so, it assumes that it's a JSON string and you already ran to_json
, and passes the string along. If not, it runs to_json
on the object.
我认为文档可能应该澄清这一点,但是您已经掌握了.尽管乍看之下并不完全直观,但如果以其他方式起作用,我会感到惊讶.
I think the documentation should probably clarify that, but there you have it. Though it's not exactly intuitive at first glance, I would be surprised if it worked any other way.
这篇关于渲染:json => “在这里串"的预期结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!