r - R中的嵌套JSON,无法解压缩天气数据
问题描述
我正在尝试从 NOAA 解开天气警报。
https://api.weather.gov/alerts
library(jsonlite)
#API
string = "https://api.weather.gov/alerts"
#import json and flatten
json_data <- fromJSON(string,flatten=TRUE)
#get names
names(json_data)
[1] "@context" "type" "features" "title" "updated"
#extract the features
final_data <- as.data.table(json_data$features)
这会生成一个表格,我可以从中获取有关每个警报的详细信息。然而,一些结果被进一步嵌套。例如:
head(final_data$properties.geocode.UGC,1)
[[1]]
[1] "AMZ732" "AMZ741" "AMZ715" "AMZ725" "AMZ712" "AMZ710"
我想解压这些并旋转表格,所以每一行都应该是:
warning | properties.geocode.UGC
storm | AMZ732
storm | AMZ741
storm | AMZ715
storm | AMZ725
storm | AMZ712
storm | AMZ710
我该怎么做?它会涉及取消列出该列吗?
解决方案
听起来您不需要GeoJSON,因此我们将使用 JSON-LD 端点:
httr::GET(
url = "https://api.weather.gov/alerts",
httr::accept("application/ld+json")
) -> res
x <- jsonlite::fromJSON(rawToChar(httr::content(res)))[["@graph"]]
x <- cbind.data.frame(x, x$geocode, x$parameters)
x$geocode <- NULL
x$parameters <- NULL
colnames(x) <- make.names(colnames(x), unique=TRUE)
x <- tidyr::unnest(x, UGC)
dplyr::data_frame(
id = x$id,
event = x$event,
ugc = x$UGC
)
## # A tibble: 1,792 x 3
## id event ugc
## <chr> <chr> <chr>
## 1 NWS-IDP-PROD-3212197-2821047 Freeze Warning NMZ538
## 2 NWS-IDP-PROD-KEEPALIVE-22857 Test Message MDC031
## 3 NWS-IDP-PROD-3212196-2821046 Special Marine Warning GMZ650
## 4 NWS-IDP-PROD-3212196-2821046 Special Marine Warning GMZ670
## 5 NWS-IDP-PROD-3212195-2821045 Wind Advisory UTZ019
## 6 NWS-IDP-PROD-3212194-2821044 Red Flag Warning CAZ211
## 7 NWS-IDP-PROD-3212194-2821044 Red Flag Warning CAZ204
## 8 NWS-IDP-PROD-3212194-2821044 Red Flag Warning CAZ283
## 9 NWS-IDP-PROD-3212194-2821044 Red Flag Warning CAZ277
## 10 NWS-IDP-PROD-3212194-2821044 Red Flag Warning CAZ203
## # ... with 1,782 more rows
推荐阅读
- java - Java 库维护/更改是否可能不影响使用它的应用程序?
- julia - Julia 1.0.0 解析函数溢出错误似乎很奇怪
- mongodb - mongodb 在数组中使用聚合
- loops - 为什么我的变量在我的循环中没有增加?
- coq - 带有 impl 的 setoid_rewrite 不适用于 `A -> B` 类型的引理
- r - 如何使用 R 中的一些嵌套因子来处理不平衡的 Model II 和 Model III 分析?
- excel - countif 使用过滤列 vba 更改
- javascript - Mocha 是否提供参数化测试“@Theory”样式的选项?
- plot - 在八度音阶上绘制透明度补丁
- excel - 如何在vba中引用复制对象将粘贴到的空间?