1. 1. Import package to work with JSON and lists
  2. 2. Load file into script
  3. 3. Extract data

Reading Local JSON Files in R

The following example is a way of reading local JSON files into R scripts. This can be useful for config files, although it’s still also acceptable for data files as well.

Import package to work with JSON and lists

1
2
require(rlist)
require(rjson)

Load file into script

1
2
3
configPath <- '.'
fileName <- 'config.json'
jsonFile <- fromJSON(file=paste(configPath,fileName,sep="/"),method="C")

The data gets loaded in as a list. It may be tedious to access nested contents via indices. To aid with this, a helper function can be created to extract the individual nested data elements of the file.

1
2
3
4
5
6
#Extract values form nested list
#top_level = list.select(obj$topkey,obj$subkey)
extractData <- function(top_level) {
output <- unlist(lapply(top_level,'[[',1));
return(output);
}

Extract data

Below is a default sample json file that includes both nested and non-nested data.

1
2
3
4
5
6
{
"port": 2100,
"connectionStrings": {
"default": "123.567.890"
}
}

The data in that file can be accessed as shown below.

1
2
3
4
5
#Not Nested
port <- config$port # Should store 2100

#Nested
connectionString <- extractData(list.select(config$connectionStrings,default)) #Should store 123.567.890