Ruby Grape:json输出被转义

时间:2013-07-19 22:18:32

标签: ruby grape grape-api

我正在研究示例Ruby / Grape示例,除了json服务转义之外,一切正常。我是全新的红宝石及其框架(仅3天),很抱歉,如果这个问题是补救性的并且提前感谢你

我相当确定不应该转义引号,无论如何这里是转义输出:

"{\"word\":\"test\",\"sentiment\":\"unkown\"}"

我的代码

require 'rubygems'
require 'grape'
require 'json'

class SentimentApiV1  < Grape::API
  version 'v1', :using => :path, :vendor => '3scale'
  format :json

  resource :words do
    get ':word' do
        {:word => params[:word], :sentiment => "unkown"}.to_json
    end

    post ':word' do
      {:word => params[:word], :result => "thinking"}.to_json
    end 
  end

  resource :sentences do
    get ':sentence' do
      {:sentence => params[:sentence], :result => "unkown"}.to_json
    end
  end

end

config.ru

  

$:。unshift“./ app”

     

要求'sentimentapi_v1.rb'

     

运行SentimentApiV1

包和版本

C:\Ruby-Projects\GrapeTest>bundle install
Using i18n (0.6.4)
Using minitest (4.7.5)
Using multi_json (1.7.7)
Using atomic (1.1.10)
Using thread_safe (0.1.0)
Using tzinfo (0.3.37)
Using activesupport (4.0.0)
Using backports (3.3.3)
Using builder (3.2.2)
Using daemons (1.1.9)
Using descendants_tracker (0.0.1)
Using hashie (2.0.5)
Using multi_xml (0.5.4)
Using rack (1.5.2)
Using rack-accept (0.4.5)
Using rack-mount (0.8.3)
Using virtus (0.5.5)
Using grape (0.5.0)
Using json (1.8.0)
Using thin (1.5.1)
Using bundler (1.3.5)

我正在运行ruby 2.0,grape .5,windows 8 64bit

3 个答案:

答案 0 :(得分:4)

转发的原因是因为您最后不需要#to_json调用,因为在第7行您指定format :json作为输出格式。

答案 1 :(得分:1)

很好 - 显然最后不需要to_json。也许是双重逃避或类似的东西。该演示肯定有to_json,所以就是这样。

require 'rubygems'
require 'grape'
require 'json'

class SentimentApiV1  < Grape::API
  version 'v1', :using => :path, :vendor => '3scale'
  format :json

  resource :words do
    get ':word' do
        {:word => params[:word], :sentiment => "unkown"}
    end

    post ':word' do
      {:word => params[:word], :result => "thinking"}
    end 
  end

  resource :sentences do
    get ':sentence' do
      {:sentence => params[:sentence], :result => "unkown"}
    end
  end

end

答案 2 :(得分:1)

您的结果"{\"word\":\"test\",\"sentiment\":\"unkown\"}"实际上是有效的JSON。这是字符串{"word":"test","sentiment":"unkown"}。通过调用to_json,您已将哈希转换为字符串,然后Grape将返回您给它的内容。使用as_json代替将返回哈希值,Grape将负责正确序列化。