</>
Skip to content
R lessons (25/41)

R — JSON

XML

library(xml2)

# Read XML
xml <- read_xml("<root><item>1</item><item>2</item></root>")

# Find elements
items <- xml_find_all(xml, "//item")
xml_text(items)

# Create XML
doc <- xml_new_root("root")
xml_add_child(doc, "item", text = "1")
xml_add_child(doc, "item", text = "2")

JSON

library(jsonlite)

# Parse JSON
json_str <- '{"name": "Alice", "age": 30}'
data <- fromJSON(json_str)

# Create JSON
data <- list(name = "Alice", age = 30)
json_str <- toJSON(data, auto_unbox = TRUE, pretty = TRUE)

# Write to file
write(json_str, "data.json")

Nested data

library(jsonlite)

json_str <- '
[
  {"name": "Alice", "scores": [90, 85, 88]},
  {"name": "Bob", "scores": [75, 80, 82]}
]'

data <- fromJSON(json_str)
print(data)

Mini Practice

Write R code that:

  1. Reads XML and extracts elements
  2. Parses JSON data
  3. Creates JSON from a list
  4. Handles nested JSON structures

Up Next

In the next lesson, you'll learn about APIs — connecting to web APIs.

Related Topics

Frequently Asked Questions about JSON

What is JSON in R?

JSON is a fundamental concept in R. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn JSON?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn JSON.

Why is JSON important in R?

JSON is essential for R development. Understanding this concept will help you write better code and solve real-world problems more effectively.