Extract information from JSON file by making get requests in r

我的未来我决定 提交于 2019-12-11 10:54:54

问题


I am trying to make a get request, and interpret this in JSON but I cannot. I think this is because "swagger" is an HTTP response, but I don't know how to parse this.

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=""))

I need the input schema from a JSON document that looks something like this

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

回答1:


You're really close. I'd prefer using httr (which implicitly uses 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()


来源:https://stackoverflow.com/questions/31258617/extract-information-from-json-file-by-making-get-requests-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!