在R中移除GeoJSON首尾方括号[]及导入为sp空间对象求助
Got it, let's tackle this problem step by step. The core issue here is that the StreamStats API response doesn't return a pure standard GeoJSON FeatureCollection—it wraps the relevant spatial data in an extra top-level array and includes non-GeoJSON metadata, which breaks direct conversion to sp objects. Here are two reliable solutions:
Solution 1: Extract Features Directly from Parsed JSON (Recommended)
This method avoids manual string manipulation by leveraging jsonlite's ability to parse nested JSON structures, pulling out only the spatial features we need:
Step 1: Install Required Packages (if missing)
install.packages(c("jsonlite", "sf", "sp"))
Step 2: Fetch, Parse, and Convert Data
library(jsonlite) library(sf) library(sp) # Fetch and parse the full API response streamstats_response <- 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" ) # Extract the standard GeoJSON features (this skips the extra wrapper array and metadata) watershed_features <- streamstats_response$features # Convert to sf first (modern spatial framework), then to sp object watershed_sf <- st_as_sf(watershed_features) watershed_sp <- as(watershed_sf, "Spatial") # Verify the result class(watershed_sp) # Should return "SpatialPolygonsDataFrame" or similar plot(watershed_sp) # Visualize to confirm the watershed geometry
Solution 2: Manual String Cleaning (Alternative)
If you prefer to directly manipulate the raw JSON string to remove the top-level brackets, use httr to fetch the raw text first:
library(httr) library(jsonlite) library(rgdal) library(sp) # Fetch raw JSON string raw_response <- GET( "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" ) json_text <- content(raw_response, "text", encoding = "UTF-8") # Remove leading and trailing square brackets cleaned_json <- substr(json_text, 2, nchar(json_text) - 1) # Parse cleaned JSON and extract features parsed_data <- fromJSON(cleaned_json) watershed_features <- parsed_data$features # Convert directly to sp using rgdal watershed_sp <- readOGR(dsn = watershed_features, layer = "OGRGeoJSON")
Why This Works
The StreamStats API wraps its GeoJSON output in an array ([]) and includes extra metadata fields (like service status info) that aren't part of the official GeoJSON spec. By extracting the features sub-element (either from the parsed JSON or cleaned string), we isolate the valid spatial data that can be converted to sp objects using standard spatial packages.
内容的提问来源于stack exchange,提问作者Ryan

