HTML and JSON

Author

Antik Salimullah

Importing HTML & JSON into R

library(rvest)
library(jsonlite)

# Read HTML table
html_data <- read_html("books.html") |>
  html_element("table") |>
  html_table()

# Read JSON data
json_data <- fromJSON("books.json")

# Display both data frames
html_data
# A tibble: 3 × 5
  Title                                            Authors  Year Publisher Genre
  <chr>                                            <chr>   <int> <chr>     <chr>
1 Destined for War: Can America and China Escape … Graham…  2017 Houghton… Inte…
2 The Hundred-Year Marathon: China's Secret Strat… Michae…  2015 Henry Ho… Inte…
3 The China Questions: Critical Insights into a R… Jennif…  2018 Harvard … Inte…
json_data
                                                                                           Title
1                              Destined for War: Can America and China Escape Thucydides's Trap?
2 The Hundred-Year Marathon: China's Secret Strategy to Replace America as the Global Superpower
3                                     The China Questions: Critical Insights into a Rising Power
                           Authors Year                 Publisher
1                   Graham Allison 2017 Houghton Mifflin Harcourt
2                Michael Pillsbury 2015        Henry Holt and Co.
3 Jennifer Rudolph; Michael Szonyi 2018  Harvard University Press
                    Genre
1 International Relations
2 International Relations
3 International Relations

Comparison Code

# Compare the original data frames
identical(html_data, json_data)
[1] FALSE
# Convert HTML tibble to a regular data frame
html_data <- as.data.frame(html_data)

# Compare again
identical(html_data, json_data)
[1] TRUE

Comparing HTML and JSON Data

I created two files containing information about three books on US-China relations. Both files were successfully imported into R with three rows and five columns.

Initially, the identical() function returned FALSE because the HTML data was imported as a tibble, while the JSON data was imported as a regular data frame.

After converting the HTML tibble using as.data.frame(), the comparison returned TRUE. This confirms that both files contain identical data.