简体   繁体   English

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

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

I am accessing one of my Rails actions from the Rails console: 我正在从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

The action is supposed to be returning a hash in JSON, not a string. 该操作应该返回JSON中的哈希,而不是字符串。 Here is the how the action ends: 操作结束的方法如下:

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

Why would this be coming through as a string? 为什么这会以字符串形式出现? I'm using Rails 3.2.0 and Ruby 1.9.3. 我正在使用Rails 3.2.0和Ruby 1.9.3。

You will always get a String from an HTTP request. 您将始终从HTTP请求中获取字符串。 render :json just converts the hash into a JSON String. render :json只是将哈希转换为JSON字符串。

You need to do JSON.parse on the String. 您需要在String上执行JSON.parse

It return JSON, because whole HTTP messages are string based. 它返回JSON,因为整个HTTP消息都是基于字符串的。 So to get JSON object in console you need call JSON.parse on response body. 因此,要在控制台中获取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