weixin_33674976 2017-12-14 21:52 采纳率: 0%
浏览 66

从Ajax通话中获取结果

Maybe this is a really stupid question but I want to use an ajax call and work with the result in R. Here is the call from www.randomuser.me:

$.ajax({
  url: 'https://randomuser.me/api/?format=csv?results=5000',
  dataType: 'json',
  success: function(data) {
    console.log(data);
  }
});

So what is the easiest way for me to save the csv so I can then work with it in R? Is that possible directly in R? I would really appreciate a low level answer (I have no idea what jQuery etc. is)

  • 写回答

2条回答 默认 最新

  • 北城已荒凉 2017-12-14 23:06
    关注

    Use the rjson package to query that URL and parse the returned JSON data into an R list:

    > library(rjson)
    > url = "https://randomuser.me/api/?format=csv?results=5000"
    > data = rjson::fromJSON(file=url)
    > str(data)
    List of 2
     $ results:List of 1
      ..$ :List of 12
      .. ..$ gender    : chr "female"
      .. ..$ name      :List of 3
    

    Note the format and results parameters are ignored here, because your URL query string is format=csv?results=5000, and you should separate parameters with &, not ?.

    If you want to read from a CSV source, fix the URL and then read from the URL:

    > url2 = "https://randomuser.me/api/?format=csv&results=5"
    > d = read.csv(url2)
    
    > dim(d)
    [1]  5 25
    > names(d)
     [1] "gender"            "name.title"        "name.first"       
     [4] "name.last"         "location.street"   "location.city"    
     [7] "location.state"    "location.postcode" "email"            
    [10] "login.username"    "login.password"    "login.salt"       
    [13] "login.md5"         "login.sha1"        "login.sha256"     
    [16] "dob"               "registered"        "phone"            
    [19] "cell"              "id.name"           "id.value"         
    [22] "picture.large"     "picture.medium"    "picture.thumbnail"
    [25] "nat"              
    > 
    
    评论

报告相同问题?