【问题标题】:Why is this Rails action returning a string instead of JSON?为什么这个 Rails 动作返回一个字符串而不是 JSON?
【发布时间】:2012-12-28 03:55:04
【问题描述】:

我正在从 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。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3


    【解决方案1】:

    您总是会从 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
      #}
      

      【讨论】:

        猜你喜欢
        • 2017-09-19
        • 2020-04-08
        • 1970-01-01
        • 1970-01-01
        • 2013-01-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多