Working with JSON Files in R Programming

JSON format has become a popular format for data exchange between applications because JSON is human readable while being concise.

Install rjson

To work with JSON Files in R programming language, you may have to install rjson package.

Open R command window, and run the following command :

</>
Copy
  install.packages("rjson")

Output

trying URL 'https://mran.microsoft.com/snapshot/2017-09-01/bin/windows/contrib/3.4/rjson_0.2.15.zip'
Content type 'application/zip' length 564436 bytes (551 KB)
downloaded 551 KB

package ‘rjson’ successfully unpacked and MD5 sums checked

The downloaded binary packages are in
	C:\Users\tutorialkart\AppData\Local\Temp\RtmpAruPYG\downloaded_packages

Read JSON File in R

To read JSON data from file in R programming language, import the rjson library, use fromJSON() function with the path to JSON File as argument.

example.R

</>
Copy
# load rjson package
library(rjson)

# read json file to variable
jsonData <- fromJSON(file = "sample-data.json")

# print json data
print(jsonData)

Output

</>
Copy
[
{"name":"R Tutorial", "category":"Programming"},
{"name":"Go Tutorial", "category":"Programming"}
]

Console

</>
Copy
> # Print the result.
> print(jsonData)
[[1]]
[[1]]$name
[1] "R Tutorial"

[[1]]$category
[1] "Programming"


[[2]]
[[2]]$name
[1] "Go Tutorial"

[[2]]$category
[1] "Programming"


>

Write JSON Object to File

To write JSON Object to file, use toJSON() function of rjson library to prepare a JSON object and then use write() function for writing the JSON object to a local file.

example.R

</>
Copy
# load rjson package
library(rjson)

list1 <- vector(mode="list", length=2)
list1[[1]] <- c("apple", "banana", "rose")
list1[[2]] <- c("fruit", "fruit", "flower")

# read list ot json
jsonData <- toJSON(list1)

# write json object to file
write(jsonData, "output.json")

Output

[["apple","banana","rose"],["fruit","fruit","flower"]]

Conclusion

In this R Tutorial – Working with JSON Files, we have learnt to read JSON data from a JSON file and write a JSON Object to a local File using rjson library with example R scripts.