In the simplest setting, fromJSON() can convert character strings that represent JSON data into a nicely structured R list. Give it a try!
# Load the jsonlite package
library(jsonlite)
# wine_json is a JSON
wine_json <- '{"name":"Chateau Migraine", "year":1997, "alcohol_pct":12.4, "color":"red", "awarded":false}'
# Convert wine_json into a list: wine
wine<-fromJSON(wine_json)
# Print structure of wine
str(wine)
As Filip showed in the video, fromJSON() also works if you pass a URL as a character string or the path to a local file that contains JSON data. Let's try this out on the Quandl API, where you can fetch all sorts of financial and economical data.
# jsonlite is preloaded
# Definition of quandl_url
quandl_url <- "https://www.quandl.com/api/v3/datasets/WIKI/FB/data.json?auth_token=i83asDsiWUUyfoypkgMz"
# Import Quandl data: quandl_data
quandl_data<-fromJSON(quandl_url)
# Print structure of quandl_data
str(quandl_data)
# The package jsonlite is already loaded
# Definition of the URLs
url_sw4 <- "http://www.omdbapi.com/?apikey=ff21610b&i=tt0076759&r=json"
url_sw3 <- "http://www.omdbapi.com/?apikey=ff21610b&i=tt0121766&r=json"
# Import two URLs with fromJSON(): sw4 and sw3
sw4 <- fromJSON(url_sw4)
sw3 <- fromJSON(url_sw3)
sw4$Title
sw3$Title
sw4$Year>sw3$Year
# jsonlite is already loaded
# Challenge 1
json1 <- '[1, 2,3, 4, 5,6]'
fromJSON(json1)
# Challenge 2
json2 <- '{"a": [1, 2, 3],"b":[4,5,6]}'
fromJSON(json2)
# Challenge 1
json1 <- '[[1, 2], [3, 4]]'
fromJSON(json1)
# Challenge 2
json2 <- '[{"a": 1, "b": 2}, {"a": 3, "b": 4}, {"a": 5, "b": 6}]'
fromJSON(json2)
Apart from converting JSON to R with fromJSON() , you can also use toJSON() to convert R data to a JSON format. In its most basic use, you simply pass this function an R object to convert to a JSON. The result is an R object of the classjson, which is basically a character string representing that JSON.
# URL pointing to the .csv file
url_csv <- "http://s3.amazonaws.com/assets.datacamp.com/production/course_1478/datasets/water.csv"
# Import the .csv file located at url_csv
water<-read.csv(url_csv,stringsAsFactors=F)
# Convert the data file according to the requirements
water_json<-toJSON(water)
# Print out water_json
water_json
# Convert mtcars to a pretty JSON: pretty_json
pretty_json<-toJSON(mtcars,pretty=TRUE)
# Print pretty_json
pretty_json
# Minify pretty_json: mini_json
mini_json<-toJSON(mtcars)
# Print mini_json
mini_json