背景:
我使用HTTParty在接受application/json的API上执行POST请求
我的身体就像那样(像个哈希)
{:contact_id =>"12345679",
:items=> [
{:contact_id=>"123456789", :quantity=>"1", :price=>"0"},
{:contact_id=>"112315475", :quantity=>"2", :price=>"2"}
]}发行:
当我编写以下代码时,这是可行的:
HTTParty.post('https://some-url', body: content.to_json, headers: { "Content-Type" => "application/json" } )但是,当只将标头中的=>符号更改为:符号时,这是不起作用的( API响应说缺少一些参数)
HTTParty.post('https://some-url', body: content.to_json, headers: { "Content-Type": "application/json" } )问题:
为什么将"Content-Type" => "application/json"更改为"Content-Type": "application/json"会导致错误?
我认为这是我不明白的Ruby散列。
编辑:
我想我的问题不是为什么哈希中的字符串键被转换为符号?的翻版
对于HTTParty使用者来说,重要的是要知道HTTParty不接受标头的符号,而只接受字符串。
有关更多信息,请参见当我尝试在头上使用新的哈希语法时,Content不会发送和在HTTparty中传递头和查询参数
谢谢你@其他人
发布于 2019-01-17 09:09:26
Ruby中的散列键可以是任何对象类型。例如,它们可以是字符串,也可以是符号。在哈希键中使用冒号(:)可以告诉Ruby您使用的是一个符号。对密钥使用字符串(或其他对象类型,如Integer)的唯一方法是使用散列火箭(=>)。
当您输入{ "Content-Type": "application/json" }时,Ruby将将字符串"Content-Type"转换为符号:"Content-Type"。您可以在控制台中看到这一点:
{ "Content-Type": "application/json" }
=> { :"Content-Type" => "application/json" }当您使用散列火箭时,它不会被转换,并且仍然是一个字符串:
{ "Content-Type" => "application/json" }
=> { "Content-Type" => "application/json" }HTTParty 不适用于符号键。.
https://stackoverflow.com/questions/54232161
复制相似问题