【发布时间】:2018-01-11 17:26:36
【问题描述】:
我可以访问 azure 中的一些遥测数据(特别是使用移动应用程序的客户的所有 API 调用)。我已经使用 R 中的 httr 包在 3 分钟内请求数据并像这样评估响应(显然有我自己的应用程序 ID 和密钥,我没有在下面包含):
install.packages("httr")
library(httr)
r1 <- GET("https://api.applicationinsights.io/v1/apps/application-ID/query?timespan=PT0.05H&query=requests", add_headers("X-Api-Key" = "my-unique-key"))
r1
####### response object ########
# Response [https://api.applicationinsights.io/v1/apps/application-ID/query?timespan=PT0.05H&query=requests]
# Date: 2018-01-11 15:55
# Status: 200
# Content-Type: application/json; charset=utf-8
# Size: 84.7 kB
在环境窗口中,我可以看到 r1 是一个 10 的列表,并且有 84,652 个原始值:
我也可以使用内容功能查看我有一个1的列表:
r2 <- content(r1)
我真的有两个问题:
1) 如何理解环境窗口中的这些输出?他们告诉我关于我的数据结构的什么(我认为它是基于内容类型描述的 JSON)
2) 有没有办法检索数据并将其转换为表格格式(数据框)?我不明白如何查询数据。我阅读了这篇文章,但无法将其应用于我的数据:https://tclavelle.github.io/blog/r_and_apis/
任何帮助将不胜感激。
2018 年 1 月 19 日更新
我使用了 jalind 的建议。代码和输出见下文:
library(httr)
library(jsonlite)
r1 <- GET("https://api.applicationinsights.io/v1/apps/application-ID/query?timespan=PT0.05H&query=requests", add_headers("X-Api-Key" = "my-unique-key"))
#convert to a character string
r2 <- rawtoChar(r1$content)
#check the class is character
class(r2)
# now extract JSON from string object
r3 <- fromJSON(r2)
# convert to a data frame - this returns a data frame with columns called name, columns and rows
x <- as.data.frame(r3[[1]])
# column headings data frame (there are 37 columns - see example of first 3 columns below):
c <- as.data.frame(x$columns)
# name type
# timestamp datetime
# id string
# source string
# data frame with 37 columns and all rows of telemetry data (only showing first 4 columns of this data frame):
r <- as.data.frame(x$rows)
# X1 X2 X3 X4
# 1 2018-01-19T10:29:25.4Z |aticCNxxxx=.f83assss_ <NA> GET /Cards/Cardtype1
# 2 2018-01-19T10:29:30.226Z |tX6Xz0xxxxx=.27cxcxae_ <NA> GET /AddressLookup/Address
# 3 2018-01-19T10:29:45.327Z |OgfPbicLues=.f83a9a1f_ <NA> POST /Account/MobileDevice
# 4 2018-01-19T10:29:46.078Z |V5MwpXXxxxxx=.f83axxxx_ <NA> GET /Cards/Cardtype1
# 5 2018-01-19T10:30:00.427Z |Jok8wxxxxxx=.7be33aaa_ <NA> GET /cards/Cardtype1
【问题讨论】:
-
如果没有reproducible example,将很难为您提供帮助。我们不知道服务器返回的是什么,也不知道您希望将其放在表中的准确程度。
-
我同意上面的评论,但你可能想看看
jsonlite包 -
ID 和密钥对我来说都是个性化的,所以我无法实际提供示例(如果有意义的话)。我真的不知道如何评估 API 本身的内容
-
两点:(1) "rawtoChar" 拼写为 'rawToChar' (2) 你的 r3 已经是一个 data.frame (你可以输入
is.data.frame(r3)自己检查