通过在r中生成get请求从JSON文件中提取信息

时间:2015-07-07 02:05:46

标签: json r swagger

我正在尝试发出get请求,并在JSON中对此进行解释,但我不能。我认为这是因为" swagger"是一个HTTP响应,但我不知道如何解析它。

library(RCurl)
library(rjson)


swagger = RCurl:: getURL(
  "https://requestresponse001.cloudapp.net:443/workspaces/7e8f135f31274b7eac419bd056875c03/services/a5b003e52c924d16a2e38ade45dd0154/swagger.json?api-version=2.0", 
  .opts = list(ssl.verifyHost = FALSE,ssl.verifyPeer = FALSE,followlocation=TRUE),header = "Accept: application/json", .encoding = "UTF-8"
)
# formatswagger <- jsonlite::toJSON(jsonlite::fromJSON(swagger), pretty = TRUE)

rjson::fromJSON(paste(readLines(swagger[1]), collapse=""))

我需要来自JSON文档的输入模式,看起来像这样

  "example": {
    "Inputs": {
      "input1": [
        {
          "Class": 1.0,
          "sepal-length": 1.0,
          "sepal-width": 1.0,
          "petal-length": 1.0,
          "petal-width": 1.0
        }
      ]
    },
    "GlobalParameters": {}
  }

1 个答案:

答案 0 :(得分:2)

你真的很亲近。我更喜欢使用httr(隐式使用jsonlite):

library(jsonlite)
library(httr)

# It's a self-signed cert
set_config(config(ssl_verifypeer=0L, ssl_verifyhost=0L), override=TRUE)
resp <- GET("https://requestresponse001.cloudapp.net:443/workspaces/7e8f135f31274b7eac419bd056875c03/services/a5b003e52c924d16a2e38ade45dd0154/swagger.json?api-version=2.0")

# will parse automagically
swagger <- content(resp)

str(swagger$definitions$ExecutionRequest$example)

## List of 2
##  $ Inputs          :List of 1
##   ..$ input1:List of 1
##   .. ..$ :List of 5
##   .. .. ..$ Class       : num 1
##   .. .. ..$ sepal-length: num 1
##   .. .. ..$ sepal-width : num 1
##   .. .. ..$ petal-length: num 1
##   .. .. ..$ petal-width : num 1
##  $ GlobalParameters: Named list()