Ruby Sinatra json呈现未按预期工作

Ruby Sinatra json呈现未按预期工作,ruby,sinatra,Ruby,Sinatra,我在Sinatra遇到了一个问题,我不能用json来响应,我在任何地方都找不到好的Sinatra文档,大多数东西似乎都过时了 不管怎样,代码如下: module MemcachedManager class App < Sinatra::Base register Sinatra::Contrib helpers Sinatra::JSON get '/' do json({ hello: 'world' }) end end end

我在Sinatra遇到了一个问题,我不能用json来响应,我在任何地方都找不到好的Sinatra文档,大多数东西似乎都过时了

不管怎样,代码如下:

module MemcachedManager
  class App < Sinatra::Base
    register Sinatra::Contrib
    helpers Sinatra::JSON

    get '/' do
      json({ hello: 'world' })
    end
  end
end

MemcachedManager::App.run! if __FILE__ == $0
模块MemcachedManager
类应用程序
我得到的答复是:

"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n<html><body><p>{\"hello\":\"world\"}</p></body></html>\n"
“\n{\'hello\':\'world\'}

\n”
这里应该只有json部分。为什么它在我没有要求的情况下呈现html标记呢?

试着放置

content_type :json
json(…)
调用之前

您看到了吗

我还将此修改为:

get '/example.json', :provides => :json do
停止使用路由的HTML/XML调用。由于您使用的是sinatra contrib gem,而且Ruby不需要所有这些参数,因此您还可以简化您作为示例给出的代码:

require 'sinatra/json'

module MemcachedManager    
  class App < Sinatra::Base
    helpers Sinatra::JSON
    get '/', :provides => :json do
      json hello: 'world'
    end
  end
end

MemcachedManager::App.run! if __FILE__ == $0
需要'sinatra/json'
MemcachedManager模块
类应用程序:json do
json你好:“世界”
结束
结束
结束
MemcachedManager::App.run!如果文件=0美元

您是否配置了一些布局?@thiagofm-您找到了这个问题的答案吗?仍然得到\n{“你好”:“世界”}

\n@thiagofm你用什么来提出请求?RSpec?卷曲Chrome…?我只是进入页面并获取其响应体。
require 'sinatra/json'

module MemcachedManager    
  class App < Sinatra::Base
    helpers Sinatra::JSON
    get '/', :provides => :json do
      json hello: 'world'
    end
  end
end

MemcachedManager::App.run! if __FILE__ == $0