Easy Tutorial
❮ R Package R Scatterplots Charts ❯

R JSON File

JSON: JavaScriptObjectNotation (JavaScript Object Notation).

JSON is a syntax for storing and exchanging text information.

JSON is similar to XML but is smaller, faster, and easier to parse.

If you are not familiar with JSON, you can refer to the JSON Tutorial first.

To read and write JSON files in R, you need to install an extension package. You can install it by entering the following command in the R console:

install.packages("rjson", repos = "https://mirrors.ustc.edu.cn/CRAN/")

To check if the installation was successful:

> any(grepl("rjson", installed.packages()))
[1] TRUE

Create a sites.json file, with the JSON file and test script in the same directory. The code is as follows:

Example

{
   "id": ["1", "2", "3"],
   "name": ["Google", "tutorialpro", "Taobao"],
   "url": ["www.google.com", "www.tutorialpro.org", "www.taobao.com"],
   "likes": [111, 222, 333]
}

To view the data, use [ ] for a specific row and [[ ]] for a specified row and column:

Example

# Load the rjson package
library("rjson")

# Get JSON data
result <- fromJSON(file = "sites.json")

# Print the result
print(result)

print("===============")

# Print the result of the first column
print(result[1])

print("===============")
# Print the result of the second row and second column
print(result[[2]][[2]])

Executing the above code outputs the following:

$id
[1] "1" "2" "3"

$name
[1] "Google" "tutorialpro" "Taobao"

$url
[1] "www.google.com" "www.tutorialpro.org" "www.taobao.com"

$likes
[1] 111 222 333

[1] "==============="
$id
[1] "1" "2" "3"

[1] "==============="
[1] "tutorialpro"

We can also use the as.data.frame() function to convert the JSON file data into a data frame, making it easier to manipulate the data:

Example

# Load the rjson package
library("rjson")

# Get JSON data
result <- fromJSON(file = "sites.json")

# Convert to data frame
json_data_frame <- as.data.frame(result)

print(json_data_frame)

Executing the above code outputs the following:

id   name            url likes
1  1 Google www.google.com   111
2  2 tutorialpro www.tutorialpro.org   222
3  3 Taobao www.taobao.com   333
❮ R Package R Scatterplots Charts ❯