The Wayback Machine - https://web.archive.org/web/20240717024511/https://www.geeksforgeeks.org/working-with-json-files-in-r-programming/
Open In App

Working with JSON Files in R Programming

Last Updated : 30 Jun, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

JSON stands for JavaScript Object Notation. These files contain the data in human readable format, i.e. as text. Like any other file, one can read as well as write into the JSON files. In order to work with JSON files in R, one needs to install the “rjson”  package. The most common tasks done using JSON files under rjson packages are as follows:

  • Install and load the rjson package in R console
  • Create a JSON file
  • Reading data from JSON file
  • Write into JSON file
  • Converting the JSON data into Dataframes
  • Working with URLs 

Install and load the rjson package

One can install the rjson from the R console using the install.packages() command in the following way:

install.packages("rjson")

After installing rjson package one has to load the package using the library() function as follows:

library("rjson")

Creating a JSON file 

To create a JSON file, one can do the following steps:

  • Copy the data given below into a notepad file or any text editor file. One can also create his own data as per the given format.
    { 
       "ID":["1","2","3","4","5"],
       "Name":["Mithuna","Tanushree","Parnasha","Arjun","Pankaj"],
       "Salary":["722.5","815.2","1611","2829","843.25"],
       "StartDate":["6/17/2014","1/1/2012","11/15/2014","9/23/2013","5/21/2013"],
       "Dept":["IT","IT","HR","Operations","Finance"]
    }
  • Choose “all types” as the file type and save the file with .json extension.(Example: example.json)
  • One must make sure that the information or data is contained within a pair or curly braces { } .

Reading a JSON file

In R, reading a JSON file is quite a simple task. One can extract and read the data of a JSON file very efficiently using the fromJSON() function. The fromJSON() function takes the JSON file and returns the extracted data from the JSON file in the list format by default.

Example:

Suppose the above data is stored in a file named example.json in the E drive. To read the file we must write the following code.




# Read a JSON file
  
# Load the package required to read JSON files.
library("rjson")
  
# Give the input file name to the function.
result <- fromJSON(file = "E:\\example.json")
  
# Print the result.
print(result)


Output:

$ID
[1] "1" "2" "3" "4" "5"

$Name
[1] "Mithuna"   "Tanushree" "Parnasha"  "Arjun"     "Pankaj"

$Salary
[1] "722.5"  "815.2"  "1611"   "2829"   "843.25"

$StartDate
[1] "6/17/2014"  "1/1/2012"   "11/15/2014" "9/23/2013"  "5/21/2013"

$Dept
[1] "IT"         "IT"         "HR"         "Operations" "Finance"

Writing into a JSON file 

One need to create a JSON Object using toJSON() function before he writes the data to a JSON file. To write into a JSON file use the write() function.

Example:




# Writing into JSON file.
  
# Load the package required to read JSON files.
library("rjson")
  
# creating the list
list1 <- vector(mode="list", length=2)
list1[[1]] <- c("sunflower", "guava", "hibiscus")
list1[[2]] <- c("flower", "fruit", "flower")
  
# creating the data for JSON file
jsonData <- toJSON(list1)
  
# writing into JSON file
write(jsonData, "result.json") 
  
# Give the created file name to the function
result <- fromJSON(file = "result.json")
  
# Print the result
print(result)


Output:

[[1]]
[1] "sunflower" "guava"     "hibiscus"

[[2]]
[1] "flower" "fruit"  "flower"

Converting the JSON data into Dataframes

In R, to convert the data extracted from a JSON file into a data frame one can use the as.data.frame() function. 

Example:




# Convert the file into dataframe
  
# Load the package required to read JSON files.
library("rjson")
  
# Give the input file name to the function.
result <- fromJSON(file = "E://example.json")
  
# Convert JSON file to a data frame.
json_data_frame <- as.data.frame(result)
  
print(json_data_frame)


Output:

  ID      Name Salary  StartDate       Dept
1  1   Mithuna  722.5  6/17/2014         IT
2  2 Tanushree  815.2   1/1/2012         IT
3  3  Parnasha   1611 11/15/2014         HR
4  4     Arjun   2829  9/23/2013 Operations
5  5    Pankaj 843.25  5/21/2013    Finance

Working with URLs 

One can take datasets from any websites and extract the data and use them. This can be done under any of two packages, namely RJSONIO and jsonlite.

Example:




# working with URLs
  
# import required library
library(RJSONIO)
  
# extracting data from the website
Raw <- fromJSON(
  
# extract the data node
food_market <- Raw[['data']]
  
# assembling the data into data frames
Names <- sapply(food_market, function(x) x[[14]])
head(Names)


Output:

[1] "LUCKY MART             " "CUMBERLAND FARMS 1587  "
[3] "K&M SPORTS             " "MASON&OLD RIDGE FARM   "
[5] "HAMPTON CHUTNEY CO     " "CM - HUTCHINSON        "


Previous Article
Next Article

Similar Reads

Working with XML Files in R Programming
XML which stands for Extensible Markup Language is made up of markup tags, wherein each tag illustrates the information carried by the particular attribute in the XML file. We can work with the XML files using the XML package provided by R. The package has to be explicitly installed using the following command: install.packages("XML")Creating XML f
3 min read
Working with Excel Files in R Programming
Excel files are of extension .xls, .xlsx and .csv(comma-separated values). To start working with excel files in R Programming Language, we need to first import excel files in RStudio or any other R supporting IDE(Integrated development environment). Reading Excel Files in R Programming Language First, install readxl package in R to load excel files
3 min read
Working with Binary Files in R Programming
In the computer science world, text files contain data that can easily be understood by humans. It includes letters, numbers, and other characters. On the other hand, binary files contain 1s and 0s that only computers can interpret. The information stored in a binary file can't be read by humans as the bytes in it translate to characters and symbol
5 min read
Working with CSV files in R Programming
In this article, we will discuss how to work with CSV files in R Programming Language. R CSV Files R CSV Files are text files wherein the values of each row are separated by a delimiter, as in a comma or a tab. In this article, we will use the following sample CSV file. Getting and Setting the Working Directory with R CSV Files C/C++ Code # Get the
4 min read
How to use cURL to Get JSON Data and Decode JSON Data in PHP ?
In this article, we are going to see how to use cURL to Get JSON data and Decode JSON data in PHP. cURL: It stands for Client URL.It is a command line tool for sending and getting files using URL syntax.cURL allows communicating with other servers using HTTP, FTP, Telnet, and more. Approach: We are going to fetch JSON data from one of free website,
2 min read
How to parse JSON object using JSON.stringify() in JavaScript ?
In this article, we will see how to parse a JSON object using the JSON.stringify function. The JSON.stringify() function is used for parsing JSON objects or converting them to strings, in both JavaScript and jQuery. We only need to pass the object as an argument to JSON.stringify() function. Syntax: JSON.stringify(object, replacer, space); Paramete
2 min read
What is difference between JSON.parse() and JSON.stringify() Methods in JavaScript ?
JSON.parse() converts JSON strings to JavaScript objects, while JSON.stringify() converts JavaScript objects to JSON strings. JavaScript utilizes JSON for data interchange between servers and web pages. These methods enable easy data manipulation and transport in web development. JSON.parse() MethodJSON.parse() converts a JSON string to a JavaScrip
2 min read
How to read JSON files in R
In this article, we will see How to read a JSON file in R through an example, and also we will have a look at how to convert JSON data into a data frame. As we know, in the R language, we have to install different packages to deal with other things, so the first step is nothing but installing the package rjson. Read JSON files in RStep 1: To read a
4 min read
How to Comment in JSON Files?
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. However, JSON does not have a built-in syntax for comments. This limitation can be challenging when you want to annotate your JSON data with explanations or notes for future reference. Des
2 min read
Working with JSON Data in Java
JSON stands for JavaScript Object Notation which is a lightweight text-based open standard designed which is easy for human-readable data interchange. In general, JSON is extended from JavaScript. JSON is language-independent and It is easy to read and write. The file extension of JSON is .json. Example - JSON format In the below given example, you
3 min read
Article Tags :
three90RightbarBannerImg