2013-07-19 35 views
1

我正在處理一個示例Ruby/Grape示例,並且除了json之外的所有工作都會被轉義。我是全新的紅寶石和它的框架(只有3天),所以對不起,如果這個問題是補救和提前感謝你Ruby葡萄:json輸出被轉義

我相當肯定不應該有報價逃脫,無論如何這裏是逃脫輸出:

"{\"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

$ :.不印字 「./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) 

我運行紅寶石2.0,葡萄3.5,Windows 8的64位

回答

4

的轉義發生的原因是因爲你不需要#to_json通話結束時,因爲在第7行要指定format :json作爲輸出格式。

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 
1

您的結果"{\"word\":\"test\",\"sentiment\":\"unkown\"}"實際上是有效的JSON。這是字符串{"word":"test","sentiment":"unkown"}。通過調用to_json,你已經將你的散列轉換爲一個String,然後Grape將返回你給它的東西。使用as_json代替它將返回一個散列,葡萄將負責正確地序列化它。