Unable to unnest json file to create map in r?

Viewed 51

I am new to using json in r and wanted to create map using data from it but so far I am unable to bring it to usable data structure format.

This is what I have tried:

library(jsonlite)
library(tidyverse)
ind_waterways <- jsonlite::fromJSON( url("https://raw.githubusercontent.com/india-in-data/waterways/master/ind_waterways.json"))

ind_waterways
ind_waterways %>% 
  map_if(is.data.frame, list) %>% 
  as_tibble() %>% 
  unnest()

but when I try to unnest it then I get error:

ind_waterways$features %>% 
  map_if(is.data.frame, list) %>% 
  as_tibble() %>% 
  unnest(coordinates)

Error: Can't subset columns that don't exist. x Column coordinates doesn't exist. Run rlang::last_error() to see where the error occurred.

1 Answers

Below, code uses the OP's solution until the conversion to tibble, then we do unnesting of columns individually as the structure is a bit complex i.e. involves matrix as columns in a nested list

library(dplyr)
library(jsonlite)
library(purrr)
out <- ind_waterways %>% 
  map_if(is.data.frame, list) %>% 
  as_tibble() %>%
  mutate(crs = unlist(crs)) %>% 
  unnest_wider(features, names_repair = "unique") %>%
  unnest_wider(geometry) %>%
  unnest(names(.)[3:6]) %>%
  mutate(coordinates = map(coordinates, as_tibble)) %>% 
  unnest_wider(coordinates) %>%
  unnest(c(V1, V2))  

-output

out
# A tibble: 115,318 x 7
   type...1          crs   type...3    id type          V1    V2
   <chr>             <chr> <chr>    <int> <chr>      <dbl> <dbl>
 1 FeatureCollection name  Feature      0 LineString  77.6  34.6
 2 FeatureCollection name  Feature      0 LineString  77.5  34.6
 3 FeatureCollection name  Feature      0 LineString  77.4  34.7
 4 FeatureCollection name  Feature      0 LineString  77.2  34.7
 5 FeatureCollection name  Feature      0 LineString  77.2  34.8
 6 FeatureCollection name  Feature      0 LineString  77.1  34.8
 7 FeatureCollection name  Feature      0 LineString  77.1  34.8
 8 FeatureCollection name  Feature      0 LineString  77.0  34.8
 9 FeatureCollection name  Feature      0 LineString  77.0  34.8
10 FeatureCollection name  Feature      0 LineString  76.8  34.9
# … with 115,308 more rows
Related