繁体   English   中英

为什么这个Rails操作返回一个字符串而不是JSON?

[英]Why is this Rails action returning a string instead of JSON?

我正在从Rails控制台访问我的Rails操作之一:

> @consumer = OAuth::Consumer.new(
>   x,
>   x,
>   site: "http://localhost:3000"
> )
> request = @consumer.create_signed_request(:get,"/get_user_info?email=x")
> uri = URI.parse("http://localhost:3000")
> http = Net::HTTP.new(uri.host, uri.port)
> http.request(request).body
=> "{\"first_thing\":\"Nick\",\"second_thing\":\"2012-12-26T11:41:11Z\",\"third_thing\":\"2012-12-26T11:40:03Z\"}"
> http.request(request).body.class
=> String

该操作应该返回JSON中的哈希,而不是字符串。 操作结束的方法如下:

render json: {
    first_thing: x,
    second_thing: x,
    third_thing: x
}

为什么这会以字符串形式出现? 我正在使用Rails 3.2.0和Ruby 1.9.3。

您将始终从HTTP请求中获取字符串。 render :json只是将哈希转换为JSON字符串。

您需要在String上执行JSON.parse

它返回JSON,因为整个HTTP消息都是基于字符串的。 因此,要在控制台中获取JSON对象,您需要在响应主体上调用JSON.parse

JSON.parse(http.request(request).body) # => {
#    first_thing: x,
#    second_thing: x,
#    third_thing: x
#}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM