簡體   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