-6ren">
gpt4 book ai didi

ruby - 使用 HTTParty 发送数组变量

转载 作者:数据小太阳 更新时间:2023-10-29 08:32:11 25 4
gpt4 key购买 nike

我正在使用 HTTParty 发送 POST 请求。所需的变量之一是数组。这是我用来发送的代码:

response = HTTParty.post url, :body => 
{"key"=>'XYZ123',
"content"=>
[{"placename"=>"placeholder",
"placecontent"=>"sample content"}],
etc. }

API需要看:

"content": [
{
"placename": "placeholder",
"placecontent": "sample content"
}
],

但是,当我检查 API 上收到的请求日志时,我发现我的代码正在生成:

"content": [
{
"placename": "placeholder"
},
{
"placecontent": "sample content"
}
],

如何阻止数组记录被一分为二?

谢谢。

编辑:代码的期望输出相当于:

...&content[0][placename]=placeholder&content[0][placecontent]=sample%20content...

最佳答案

默认情况下,HTTPParty 使用 HashConversionsHash 主体转换为参数:

Examples:

{ :name => "Bob",
:address => {
:street => '111 Ruby Ave.',
:city => 'Ruby Central',
:phones => ['111-111-1111', '222-222-2222']
}
}.to_params
#=> "name=Bob&address[city]=Ruby Central&address[phones][]=111-111-1111&address[phones][]=222-222-2222&address[street]=111

Ruby Ave."

您可以通过使用 HTTParty.query_string_normalizer 用您自己的转换器覆盖它:

Override the way query strings are normalized. Helpful for overriding the default rails normalization of Array queries.

For a query:

get '/', :query => {:selected_ids => [1,2,3]}

The default query string normalizer returns:

/?selected_ids[]=1&selected_ids[]=2&selected_ids[]=3

Let’s change it to this:

/?selected_ids=1&selected_ids=2&selected_ids=3

Pass a Proc to the query normalizer which accepts the yielded query.

@example Modifying Array query strings

class ServiceWrapper
include HTTParty

query_string_normalizer proc { |query|
query.map do |key, value|
value.map {|v| "#{key}=#{v}"}
end.join('&')
}
end

@param [Proc] normalizer custom query string normalizer. @yield [Hash, String] query string @yieldreturn [Array] an array that will later be joined with ‘&’

或者简单地在你的选项中传递它:

response = HTTParty.post url, :body => 
{"key"=>'XYZ123',
"content"=>
[{"placename"=>"placeholder",
"placecontent"=>"sample content"}]},
:query_string_normalizer => -> (h) { ... your own implementation here ...}

要获得 a[1]=val1&a[2]=val2 而不是 a[]=val1&a[]=val2 的序列化,您可以创建自己的 HashConversions 基于 current one

  class MyHashConversions

def to_params(hash)
params = hash.map { |k,v| normalize_param(k,v) }.join
params.chop! # trailing &
params
end

def normalize_param(key, value)
param = ''
stack = []

if value.is_a?(Array)

#### THE CHANGE IS HERE

param << value.each_with_index.map { |element, i| normalize_param("#{key}[#{i}]", element) }.join

####
elsif value.is_a?(Hash)
stack << [key,value]
else
param << "#{key}=#{URI.encode(value.to_s, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))}&"
end

stack.each do |parent, hash|
hash.each do |k, v|
if v.is_a?(Hash)
stack << ["#{parent}[#{k}]", v]
else
param << normalize_param("#{parent}[#{k}]", v)
end
end
end

param
end
end

上面的代码没有经过测试,但如果它可以工作,并且足够通用,你可以考虑 fork 项目和 github,在那里进行修复,这样它就可以开箱即用:)

关于ruby - 使用 HTTParty 发送数组变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21856373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com