通过httr

时间:2019-01-03 13:52:24

标签: r curl rcurl httr

是否可以通过NULLhttr作为JSON参数提交?

当我执行httr::POST("https://httpbin.org/post", body = list(a = 1, b = NULL), httr::verbose(), encode = "json”)时,即使输出b = NULL是有效的R列表,并且存在{{1} }值设置为list(a = 1, b = NULL)

在Python的b库中,允许提交NULL参数,并且我使用的API取决于该行为(也许不是最明智的设计选择,但这是我必须忍受的) )。 requestsNone有什么方法或与此相关的接口吗?

1 个答案:

答案 0 :(得分:1)

这似乎是由body <- compact(body)中的httr:::body_config引起的。您可以通过不将主体作为list而不是character与json直接提供来解决。

不确定下面的代码是否返回您期望的结果,但是您可以直接将正文作为包含json的字符向量发送:

httr::POST(
  "https://httpbin.org/post",
  body = '{"a":1,"b":"None"}',
  httr::verbose(),
  encode = "json"
)

或者,“以编程方式”:

httr::POST(
  "https://httpbin.org/post",
  body = jsonlite::toJSON(list(a = 1, b = "None"), auto_unbox = TRUE),
  httr::verbose(),
  encode = "json"
)

httr:POST的body参数帮助下:https://www.rdocumentation.org/packages/httr/versions/1.4.0/topics/POST

请注意,对于jsonlite::toJSON,有一些选项可供选择,具体取决于您实际上想POST作为正文:

jsonlite::toJSON(list(a = 1, b = NA), auto_unbox = TRUE)
# {"a":1,"b":null} 

jsonlite::toJSON(list(a = 1, b = NULL), auto_unbox = TRUE)
# {"a":1,"b":{}} 

jsonlite::toJSON(list(a = 1, b = NA_integer_), auto_unbox = TRUE)
# {"a":1,"b":"NA"}

jsonlite::toJSON(list(a = 1, b = list()), auto_unbox = TRUE)
# {"a":1,"b":[]}