DEV Community

SunnahSource
SunnahSource

Posted on

Explore 22 Hadith Collections in R with jsonlite: Tidy Table, Bar Chart, CSV Export and 9 Languages

R is great for quick looks at data, and a JSON API turns into a data frame in one line with jsonlite. In this tutorial we build a small R script that reads the Hadith 22 Books API from QuraniAPI and:

  • caches the response for 24 hours (and keeps the old cache if the network fails)
  • checks the data before using it (success flag, one row per collection)
  • ranks the collections by hadith_count and groups them by compiler
  • exports hadith_books.csv (UTF-8, Arabic names kept) and hadith_books.png
  • prints the sample hadith in any of 9 languages: en, ur, fr, de, tr, ms, ru, zh-CN, ja

Only base R and jsonlite are used. Tested with R 4.5.0.

The endpoint

GET https://quranicapi.online/api/serve.php?slug=hadith-22-books&lang=all
Enter fullscreen mode Exit fullscreen mode

The response (trimmed) looks like this:

{
  "title": "Hadith — 22 Books",
  "total_books": 22,
  "books": [
    { "id": 1, "name_en": "Sahih al-Bukhari", "name_ar": "صحيح البخاري",
      "author": "Imam Bukhari", "hadith_count": 7563 }
  ],
  "sample_hadith": {
    "book": "Sahih al-Bukhari", "hadith_number": 1,
    "arabic": "إِنَّمَا الأَعْمَالُ بِالنِّيَّاتِ",
    "translations": { "en": "Actions are by intentions.", "ur": "اعمال نیتوں پر ہیں۔" }
  },
  "success": true
}
Enter fullscreen mode Exit fullscreen mode

books is an array of flat objects, so fromJSON() gives us a data frame straight away.

Setup

# Debian/Ubuntu
sudo apt-get install -y r-base-core r-cran-jsonlite
# or, inside R:
# install.packages("jsonlite")
Enter fullscreen mode Exit fullscreen mode

The script

Save this as hadith_books.R:

#!/usr/bin/env Rscript
# Explore the QuraniAPI "Hadith - 22 Books" sample in R (base R + jsonlite)
suppressPackageStartupMessages(library(jsonlite))

API   <- "https://quranicapi.online/api/serve.php?slug=hadith-22-books&lang=all"
CACHE_DIR <- path.expand(Sys.getenv("XDG_CACHE_HOME", "~/.cache"))
dir.create(CACHE_DIR, showWarnings = FALSE, recursive = TRUE)
CACHE <- file.path(CACHE_DIR, "hadith-22-books.json")
LANGS <- c("en", "ur", "fr", "de", "tr", "ms", "ru", "zh-CN", "ja")

args <- commandArgs(trailingOnly = TRUE)
lang <- if (length(args) >= 1) args[1] else "en"
top  <- if (length(args) >= 2) as.integer(args[2]) else 10L
if (!lang %in% LANGS) stop("lang must be one of: ", paste(LANGS, collapse = ", "))

# 1. Fetch with a 24h file cache (the sample changes rarely)
fetch_json <- function(url, path, max_age_h = 24) {
  fresh <- file.exists(path) &&
    difftime(Sys.time(), file.mtime(path), units = "hours") < max_age_h
  if (!fresh) {
    tmp <- paste0(path, ".part")
    ok <- tryCatch({
      download.file(url, tmp, quiet = TRUE, mode = "wb")
      fromJSON(tmp)            # validate before replacing the cache
      file.rename(tmp, path)
    }, error = function(e) { message("fetch failed: ", conditionMessage(e)); FALSE })
    if (!isTRUE(ok) && !file.exists(path)) stop("no data and no cache")
  }
  fromJSON(path, simplifyDataFrame = TRUE)
}

d <- fetch_json(API, CACHE)
stopifnot(isTRUE(d$success), is.data.frame(d$books))
books <- d$books

# 2. Defensive checks: one row per collection
dup <- duplicated(books[, c("name_ar", "author")])
if (any(dup)) message("note: dropping ", sum(dup), " duplicate row(s): ",
                      paste(books$name_en[dup], collapse = ", "))
books <- books[!dup, ]

# 3. Table: biggest collections first
books <- books[order(-books$hadith_count), ]
cat(sprintf("%s: %d collections, %s hadith in total\n\n", d$title, nrow(books),
            format(sum(books$hadith_count), big.mark = ",")))
print(head(books[, c("name_en", "author", "hadith_count")], top), row.names = FALSE)

# 4. Group by compiler
by_author <- aggregate(hadith_count ~ author, data = books, FUN = sum)
by_author$books <- as.vector(table(books$author)[by_author$author])
by_author <- by_author[order(-by_author$books, -by_author$hadith_count), ]
cat("\nCompilers with more than one collection:\n")
print(subset(by_author, books > 1), row.names = FALSE)

# 5. Export CSV (UTF-8, keeps the Arabic names) and a bar chart
write.csv(books, "hadith_books.csv", row.names = FALSE, fileEncoding = "UTF-8")
png("hadith_books.png", width = 900, height = 600)
par(mar = c(5, 14, 3, 2))
b <- head(books, top)
barplot(rev(b$hadith_count), names.arg = rev(b$name_en), horiz = TRUE, las = 1,
        col = "#1b7f5b", main = sprintf("Top %d hadith collections by size", top),
        xlab = "hadith_count")
invisible(dev.off())

# 6. The sample hadith in the requested language
s <- d$sample_hadith
cat(sprintf("\nSample: %s #%d\n%s\n%s\n", s$book, s$hadith_number, s$arabic,
            s$translations[[lang]]))
cat("\nWrote hadith_books.csv and hadith_books.png\n")
Enter fullscreen mode Exit fullscreen mode

A few things worth pointing out:

  • Validate before caching. The download goes to a .part file and is only renamed after fromJSON() parses it, so a broken response never replaces a good cache.
  • Stale cache beats no data. If the network fails and a cache exists, the script just uses it.
  • Check your assumptions. duplicated() on name_ar + author makes sure every collection is counted once before you sum anything. It is a cheap habit that saves wrong totals in any data pipeline.
  • Keep UTF-8. fileEncoding = "UTF-8" keeps the Arabic names readable when the CSV is opened in a spreadsheet or loaded back with read.csv(..., encoding = "UTF-8").

Run it

Rscript hadith_books.R en 10
Enter fullscreen mode Exit fullscreen mode

Output:

note: dropping 1 duplicate row(s): Al-Adab al-Mufrad
Hadith — 22 Books: 21 collections, 158,029 hadith in total

                  name_en          author hadith_count
 Musannaf Ibn Abi Shaybah Ibn Abi Shaybah        37000
             Musnad Ahmad      Imam Ahmad        28000
            Sunan Bayhaqi      Al-Bayhaqi        21000
          Mustadrak Hakim        Al-Hakim         9045
         Sahih Ibn Hibban      Ibn Hibban         7600
         Sahih al-Bukhari    Imam Bukhari         7563
             Sahih Muslim     Imam Muslim         7453
       Mishkat al-Masabih      At-Tabrizi         6294
           Sunan an-Nasai        An-Nasai         5761
          Sunan Abu Dawud       Abu Dawud         5274

Compilers with more than one collection:
       author hadith_count books
   Al-Bayhaqi        22500     2
 Imam Bukhari         8885     2
  At-Tirmidhi         4358     2
    An-Nawawi         1934     2

Sample: Sahih al-Bukhari #1
إِنَّمَا الأَعْمَالُ بِالنِّيَّاتِ
Actions are by intentions.

Wrote hadith_books.csv and hadith_books.png
Enter fullscreen mode Exit fullscreen mode

Pick another language for the sample hadith with the first argument and change the chart size with the second:

Rscript hadith_books.R ur 8
Rscript hadith_books.R ja 5
Enter fullscreen mode Exit fullscreen mode

You now have hadith_books.csv for a spreadsheet or a dashboard, and hadith_books.png (a horizontal bar chart of the largest collections) for a README or a slide.

Ideas to extend it

  • Load the CSV into a Shiny app with a searchable table and a language picker.
  • Join it with your own reading log to track which collections you have studied.
  • Swap barplot() for ggplot2 if it is already in your toolbox.

Notes

Top comments (1)

Collapse
 
dataspryva profile image
Dataspryva •

MA Nice work, Unique collection names prove nothing about unique narrations, so a compiler's summed hadith_count is a count of entries.