I'm trying to import a geojson into R as a spatial object (i.e., sp) from a USGS web service (streamstats) and am having trouble getting it into the right format for 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")
This returns the feature in a geojson plus a bunch of other things I don't need. I can select just the data frame I need and write it out with:
tmp <- mydata$featurecollection[2,2]
write_json(tmp, 'test.json')
[{"type": "FeatureCollection", ...bunch of other stuff}]
If I manually remove the brackets "[]" on each end of the json file I can then import it as a spatial object with:
library(geojsonio)
test <- geojson_read('test.json', method='local', what='sp')
Otherwise I get this error:
Error in rgdal::ogrListLayers(input) : Cannot open data source
Is there a way to remove the brackets on each end? Maybe there's even a simpler solution I'm missing from where I select out the required data frame.
auto_unbox = TRUE
solved a similar problem I faced with multiple brackets forjsonlite::write_JSON
as well. – Eelworm