Several RESTful web services return data in JSON format, in some ways simpler and more efficient than XML. This recipe shows you how to read JSON data.
Reading JSON data
Getting ready
R provides several packages to read JSON data, but we will use the jsonlite package. Install the package in your R environment, as follows:
> install.packages("jsonlite")
If you have not already downloaded the files for this chapter, do it now and ensure that the students.json files and student-courses.json files are in your R working directory.
How to do it...
Once the files are ready, load the jsonlite package and read the files as follows:
- Load the library:
> library(jsonlite)
- Load the JSON data from the files:
> dat.1 <- fromJSON("students.json")
> dat.2 <- fromJSON("student-courses.json")
- Load the JSON document from the web:
> url <- "http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json"
> jsonDoc <- fromJSON(url)
- Extract the data into data frames:
> dat <- jsonDoc$list$resources$resource$fields
> dat.1 <- jsonDoc$list$resources$resource$fields
> dat.2 <- jsonDoc$list$resources$resource$fields
- Verify the results:
> dat[1:2,]
> dat.1[1:3,]
> dat.2[,c(1,2,4:5)]
How it works...
The jsonlite package provides two key functions: fromJSON and toJSON.
The fromJSON function can load data either directly from a file or from a web page, as the preceding steps 2 and 3 show. If you get errors in downloading content directly from the web, install and load the httr package.
Depending on the structure of the JSON document, loading the data can vary in complexity.
If given a URL, the fromJSON function returns a list object. In the preceding list, in step 4, we see how to extract the enclosed data frame.