Rya*_*yan 5 json r geojson jsonlite
我正在尝试将 geojson 作为空间对象(即 sp)从 USGS Web 服务(streamstats)导入到 R 中,但无法将其转换为 R 的正确格式。
library(jsonlite)
mydata <- fromJSON("https://streamstats.usgs.gov/streamstatsservices/watershed.geojson?rcode=NY&xlocation=-74.524&ylocation=43.939&crs=4326&includeparameters=false&includeflowtypes=false&includefeatures=true&simplify=true")
Run Code Online (Sandbox Code Playgroud)
这将返回 geojson 中的功能以及一堆我不需要的其他东西。我可以只选择我需要的数据框并将其写出:
tmp <- mydata$featurecollection[2,2]
write_json(tmp, 'test.json')
Run Code Online (Sandbox Code Playgroud)
[{"type": "FeatureCollection", ...一堆其他东西}]
如果我手动删除 json 文件两端的括号“[]”,则可以将其作为空间对象导入:
library(geojsonio)
test <- geojson_read('test.json', method='local', what='sp')
Run Code Online (Sandbox Code Playgroud)
否则我会收到此错误:
rgdal::ogrListLayers(input) 中的错误:无法打开数据源
有没有办法去掉两端的括号?也许我还缺少一个更简单的解决方案,我从中选择了所需的数据框。
另一位geojsonio作者在这里...
geojsonio我不认为任何库/包( 、等)有问题rgdal,但事实上,方括号使其不是符合规范的正确 geojson 对象(方括号表示数组)。
该 url 返回一个 json 对象,其中包含一个数组(令人困惑地称为featurecollection),然后该数组包含两个对象,每个对象包含一个name和一个特征,并且每个特征都是一个正确的geojson FeatureCollection。这些FeatureCollections就是我们想要提取的内容 - 一个 a Point(可能是分水岭的质心?),一个 aPolygon定义分水岭边界。
library(jsonlite)
library(geojsonio)
library(sp)
# Don't simplify the results so that it's easier to pull out the full geojson objects
mydata <- fromJSON("https://streamstats.usgs.gov/streamstatsservices/watershed.geojson?rcode=NY&xlocation=-74.524&ylocation=43.939&crs=4326&includeparameters=false&includeflowtypes=false&includefeatures=true&simplify=true",
simplifyVector = FALSE, simplifyDataFrame = FALSE)
# Extract each geojson object and 'auto_unbox' to remove square brackets from
# arrays of length 1:
point_geojsonsting <- toJSON(mydata$featurecollection[[1]]$feature,
auto_unbox = TRUE)
poly_geojsonsting <- toJSON(mydata$featurecollection[[2]]$feature,
auto_unbox = TRUE)
# Read directly to sp without writing to disk first:
point_sp <- geojson_sp(point_geojsonsting)
poly_sp <- geojson_sp(poly_geojsonsting)
plot(poly_sp)
plot(point_sp, add = TRUE, col = "red", pch = 21, cex = 5)
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v0.2.0)于 2018-05-09 创建。