Gem HTTParty 如何提交 JSON Array?

michael_roshen · 2017年11月01日 · 最后由 martin91 回复于 2017年11月02日 · 1927 次阅读
class Foo
  include HTTParty
end

# Simple post with full url and setting the body
Foo.post('http://foo.com/resources', body: {bar: 'baz'})

怎么 post 这种 Json Array 的参数

[
  {"name":"test1","display_name":"test1","numeric":0},
  {"name":"test2","display_name":"test2","numeric":0},
  {"name":"test3","display_name":"test3","numeric":0}
]

参数得有参数名吧

data = [
  {"name":"test1","display_name":"test1","numeric":0},
  {"name":"test2","display_name":"test2","numeric":0},
  {"name":"test3","display_name":"test3","numeric":0}
]

Foo.post('http://foo.com/resources', body: data.to_json, headers: { 'Content-Type' => "application/json" })

这样如何?

hw676018683 回复

歪个楼聊下,我试了一下,如果没有指定顶层参数这种请求,如果是 rails,那么请求自动解析后将 body 的数据放在 "_json" 参数里,我的演示:

curl -d "[{\"a\":1},{\"a\":2}]" -H "Content-Type:application/json" localhost:3000/admin/admin_users

Rails 服务器打印的日志:

Started POST "/admin/admin_users" for 127.0.0.1 at 2017-11-02 00:54:23 +0800
  ActiveRecord::SchemaMigration Load (15.8ms)  SELECT `schema_migrations`.* FROM `schema_migrations`
Processing by Admin::AdminUsersController#create as */*
  Parameters: {"_json"=>[{"a"=>1}, {"a"=>2}], "admin_user"=>{}}

另外我翻了下 rails 源码,找到了 json 解析时候的这个默认行为:

# https://github.com/rails/rails/blob/8c7aa4c7bcb4ae42db8c573ba64a5eabdf54ecd1/actionpack/lib/action_dispatch/http/parameters.rb#L11-L13
DEFAULT_PARSERS = {
    Mime[:json].symbol => -> (raw_post) {
      data = ActiveSupport::JSON.decode(raw_post)
      data.is_a?(Hash) ? data : { _json: data }
    }
  }
需要 登录 后方可回复, 如果你还没有账号请 注册新账号