Assignment – Working with XML and JSON in R

Pick three of your favorite books on one of your favorite subjects. At least one of the books should have more than one author. For each book, include the title, authors, and two or three other attributes that you find interesting.

Take the information that you’ve selected about these three books, and separately create three files which store the book’s information in HTML (using an html table), XML, and JSON formats (e.g. “books.html”, “books.xml”, and “books.json”). To help you better understand the different file structures, I’d prefer that you create each of these files “by hand” unless you’re already very comfortable with the file formats. Write R code, using your packages of choice, to load the information from each of the three sources into separate R data frames. Are the three data frames identical? Your deliverable is the three source files and the R code. If you can, package your assignment solution up into an .Rmd file and publish to rpubs.com. [This will also require finding a way to make your three text files accessible from the web]

NOTES ON WORK

Note the Json Dataframe is different from the HTML and the XML dataframes. The Json df has four rows, but its because i structured the JSON differently from the HTML and XML. The HTML and XML have the two authors as a string separated by a comma, while the JSON has the second author as its own entry.

XML ingestion

library(XML)
library(xml2)

xml_data <- read_xml("https://raw.githubusercontent.com/jhnboyy/CUNYSPS_DATA607/refs/heads/main/Week7/books.xml")
books <- xmlParse(xml_data)
books <- xmlToDataFrame(books)
books
##            title                     author published category
## 1           1984              George Orwell      1949  fiction
## 2 Fahrenheit 451               Ray Bradbury      1953  fiction
## 3   The Talisman Stephen King, Peter Straub      1984  fiction

HTML ingestion

library(rvest)

html <- read_html("https://raw.githubusercontent.com/jhnboyy/CUNYSPS_DATA607/refs/heads/main/Week7/books.html")
df <- data.frame(html_table(html))
colnames(df)<-df[1,]
df<-df[-1,]
df
##            Title                     Author Category Published
## 2           1984              George Orwell  fiction      1949
## 3 Fahrenheit 451               Ray Bradbury  fiction      1953
## 4   The Talisman Stephen King, Peter Straub  fiction      1984

JSON ingestion

library(jsonlite)

json_data <- read_json("https://raw.githubusercontent.com/jhnboyy/CUNYSPS_DATA607/refs/heads/main/Week7/books.json", simplifyVector = TRUE)
json_df = as.data.frame(json_data)
json_df
##            title        author category publication_year
## 1           1984 George Orwell  fiction             1949
## 2 Fahrenheit 451  Ray Bradbury  fiction             1953
## 3   The Talisman  Stephen King  fiction             1984
## 4   The Talisman  Peter Straub  fiction             1984