- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
我的 Grape API 接受 json 格式,我有接受 JSON 作为参数的方法:
desc 'JSON test'
params do
requires :json, type: JSON
end
post :json_test do
json = params[:json]
{result: json}
end
当我通过 postman 发出请求时,参数是原始的 application/json 内容类型:
{
"json": {"test": "test"}
}
当我发送这个时,我收到错误信息:
"json is invalid"
但是,当我这样发送时:
{
"json": "{\"test\": \"test\"}"
}
它显示了正确的响应:
{
"result": {
"test": "test"
}
}
为什么会这样?当我创建 Hash
类型时,第一个变体起作用了,但是如果我想发送 Array
的哈希/jsons 呢?我知道 Grape 不支持 Array[Hash]
类型。
最佳答案
grape 在到达您的参数 block 之前解析 application/json 数据。
在此 block 中:
params do
requires :json, type: JSON
end
你告诉 grape 你的 :json 参数应该包含一个 JSON 字符串。
所以当你发送这个时:
{
"json": {"test": "test"}
}
json包含
{"test": "test"}
这被视为一个散列,不是一个有效的 JSON 字符串,因此我们的错误。
但是当你发送这个
{
"json": "{\"test\": \"test\"}"
}
json包含
"{\"test\": \"test\"}"
这是一个有效的 JSON 字符串,然后它会很乐意为您解析为哈希。
如果你想用
{
"json": {"test": "test"}
}
在你的帖子请求中,你的参数 block 应该是这样的:
params do
requires :json, type: Hash #<-- Hash here instead of JSON since json data has already been parsed into a Hash
end
关于ruby-on-rails - 葡萄,将 JSON 作为参数发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36686659/
我正在尝试在 ruby 中创建一个 Restful json api - 所以我在 Rack 中使用 grape ( https://github.com/intridea/grape )。我没有
我正在研究一个示例 Ruby/Grape 示例,除了 json 被转义外,一切正常。我也是全新的 ruby 及其框架(仅 3 天),如果这个问题是补救性的并且提前谢谢你,我很抱歉 我相当确定不应该
我的 Grape 应用程序有几个错误处理程序,最后包括: rescue_from :all, backtrace: true do |e| message = { errors: { all: e
我有带 Grape API 的 Rails 应用。 接口(interface)由 Backbone 完成,Grape API 为其提供所有数据。 它返回的都是用户特定的东西,所以我需要引用当前登录的用
我的 Grape API 接受 json 格式,我有接受 JSON 作为参数的方法: desc 'JSON test' params do requires :json, type: JSON e
如何避免重复代码? resource 'api/publication/:publicationName' do params do requires :type, type: Strin
首先: 我正在使用 grape 构建我的 API (Rails 4)。当有人发送无效的 JSON 正文时(例如忘记最后一个 }),会引发以下错误: ActionDispatch::ParamsPars
我正在尝试让 Grape API 以 json 格式回答其所有动词。问题是我无法回答 json 格式的路由错误。我什至无法挽救 ActionController::RoutingError。 我已阅读
我正在用 grape 编写一个 API 服务器,我选择使用 grape-entity 因为它能够自动生成 swagger 的文档。但是现在我在按要求设置参数时遇到了问题。因为葡萄不验证参数是否存在。看
在 Grape 中,如果您使用 错误! 方法它会抛出一个错误并且永远不会调用 Grape::Endpoint “after”回调。 我希望应用程序在出错时调用后 Hook !已被调用。 我添加了这个中
我正在使用 Grape on Rails 4.2 构建 API。这是 GitHub 上的 repo 链接. 在前端,我有一个用 EmberJS 构建的 JavaScript 应用程序。这是 GitHu
使用 grape 从 json 创建新的 ActiveRecord 的正确方法是什么?我是否在我的用户模型中使用 attr_accessible 来避免 ActiveModel::ForbiddenA
我是一名优秀的程序员,十分优秀!