You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ruby Grape中允许接收顶层JSON数组参数

嘿,我之前正好处理过一模一样的需求!要让Ruby Grape直接接收顶层JSON数组(而不是带键的对象),你需要调整参数验证的写法——你之前的代码是在期望请求体是单个包含latitude和longitude的对象,但实际上我们要验证的是数组里的每一项元素。

正确的配置方式是用each块来定义数组元素的验证规则,这样Grape就能自动解析顶层数组并验证每个元素的结构:

params do
  # 验证数组中的每一个元素必须包含合法的latitude和longitude
  each do
    requires :latitude, type: Float
    requires :longitude, type: Float
  end
end

post '/coordinates' do
  # 此时 params 就是经过验证的完整JSON数组
  route = Route.create(coordinates: params)
  { id: route.id }
end

关键点说明:

  • 当请求体是顶层JSON数组时,Grape会自动把params解析为数组对象,不需要额外命名包裹键。
  • each块会遍历数组中的每一项,确保每个元素都符合latitude(Float类型)和longitude(Float类型)的必填要求。
  • 记得要确保请求的Content-Type头设置为application/json,否则Grape可能无法正确解析请求体。

如果需要支持可选的空数组场景,也可以用占位符参数的写法(不过第一种方式更简洁):

params do
  optional :_dummy, type: Array, default: [] do
    requires :latitude, type: Float
    requires :longitude, type: Float
  end
end

post '/coordinates' do
  route = Route.create(coordinates: params)
  { id: route.id }
end

内容的提问来源于stack exchange,提问作者Mateus Mendonça

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:27:47