【问题标题】:JSON array in "body" parameter of httr::POST()httr::POST() 的“body”参数中的 JSON 数组
【发布时间】:2019-03-05 10:06:06
【问题描述】:

我想使用 httr 包发送一个在正文中包含一些变量的发布请求。

如果是 JSON 格式,正文会是什么样子:

{a:"1", b:"2", c:[{d:"3", e:"4"}]}

我对 httr::POST() 的尝试

r <- POST("http://httpbin.org/post", body = list(a = 1, b = 2, c = list(d=3, e=4)))

我得到的错误:

Error in curl::handle_setform(handle, .list = req$fields) : 

Unsupported value type for form field 'c'.

我需要如何构造我的 POST() 语句以按照上面提到的格式发送它?

编辑:在尝试@renny 的解决方案时(我添加了 verbose() 以提高可见性),即以下行

r <- POST("http://httpbin.org/post", body = json_array, encode="json", verbose())

我能够观察到输出中生成的 JSON 格式如下:

{"post":{"a":1,"b":2,"c":{"d":3,"e":4}}}

如您所见,“c”变量周围没有 [],而是有一个“post”变量。以下是我想要的。

{"a":1,"b":2,"c":[{"d":3,"e":4}]}

【问题讨论】:

    标签: r post httr jsonlite


    【解决方案1】:

    我知道这是一个老问题,但也许有人会像我一样来到这里。问题是缺少list

    要创建一个 json 数组而不是一个对象,列表必须是未命名的。所以在你的例子中:

    > json_array <- list(a = 1, b = 2, c = list(list(d=3, e=4)))
    
    > jsonlite::toJSON(json_array)
    {"a":[1],"b":[2],"c":[{"d":[3],"e":[4]}]}
    
    # auto_unbox extracts values from unnecessary arrays, not explicit lists
    > jsonlite::toJSON(json_array, auto_unbox = T)
    {"a":1,"b":2,"c":[{"d":3,"e":4}]} 
    
    

    那么您将不需要使用jsonlite,因为编码可以完成工作:

    httr::POST("http://httpbin.org/post", body = json_array, encode="json")
    
    

    返回响应

    {
      "args": {}, 
      "data": "{\"a\":1,\"b\":2,\"c\":[{\"d\":3,\"e\":4}]}", 
      "files": {}, 
      "form": {}, 
      "headers": {
        "Accept": "application/json, text/xml, application/xml, */*", 
        "Accept-Encoding": "deflate, gzip", 
        "Content-Length": "33", 
        "Content-Type": "application/json", 
    ...
    }
    
    

    【讨论】:

      【解决方案2】:
      library(httr)
      
       json_array <- list(
            post =  list(a = 1, b = 2, c = list(d=3, e=4))
          )
      
       r <- POST("http://httpbin.org/post", body = json_array, encode="json")
      
      app_data <- content(r)
      

      试试这个。 这可能会奏效!

      【讨论】:

      • @SJEROMEGIDEON 如果您从“post”中删除列表的分配,则它不会出现。例如:json_array
      • 谢谢!这是解决了一个问题,但我希望“c”可以作为 JSON 数组使用,如编辑末尾所述。
      • 我想,你也需要使用 JSONLITE。
      • 我已更新标签以包含 jsonlite。我需要用 jsonlite 做什么来获得我需要的格式?
      【解决方案3】:

      所以我不得不使用的解决这个问题的方法是在 body 参数中使用 JSON 字符串。 例如,以下是考虑中的 JSON 字符串:

      json <- {"a":1,"b":2,"c":[{"d":3,"e":4}]}
      

      我必须将此 JSON 字符串作为 httr::POST() 的“body”参数的值传递 所以函数调用看起来像:

      r <- POST(url=url, body=json, encode="json", verbose())
      

      【讨论】:

        猜你喜欢
        • 2019-05-01
        • 2019-06-27
        • 2017-08-05
        • 2014-10-25
        • 2016-08-20
        • 1970-01-01
        • 2022-07-07
        • 2018-01-20
        • 1970-01-01
        相关资源
        最近更新 更多