2012-12-26 73 views
1

我訪問的從Rails的控制檯我的Rails操作之一:爲什麼這個Rails動作返回一個字符串而不是JSON?

> @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。

回答

2

您將始終從HTTP請求中獲取字符串。 render :json只是將散列轉換爲JSON字符串。

您需要對字符串做JSON.parse

2

它返回JSON,因爲整個HTTP消息是基於字符串的。因此,要在控制檯中獲取JSON對象,您需要在響應主體上調用JSON.parse

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