Search code examples
rubyruby-grapegrape-api

Ruby Grape: json output is escaped


I am working on a sample Ruby / Grape example, and everything works except the json is served escaped. I am brand new too ruby and its frameworks (just 3 days), so sorry if this question is remedial and thhank you in advance

I am fairly certain there shouldn't be escaping of the quotes, anyhow here is the escaped output:

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

my code

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"

require 'sentimentapi_v1.rb'

run SentimentApiV1

Packages and versions

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)

I am running ruby 2.0, grape .5, windows 8 64bit


Solution

  • The reason the escaping is happening is because you don't need the #to_json call at the end because on line 7 you are specifying format :json as the output format.