JSON (JavaScript Object Notation) file is used to exchange data between a web application and a server.
Importing data in R from a JSON file requires the rjson package that can be installed as follows:
install.packages("rjson")
For example:
#To load rjson package
library("rjson")
#To give the file name to the function
jsondata <- fromJSON(file = "Jsonfile.json")
#To print the file
print(jsondata)
Output:
$ID
[1] "1" "2" "3" "4" "5"
$Name
[1] "Sam" "Rob" "Max" "Robert" "Ivar"
$Salary
[1] "32000" "27000" "35000" "25000" "37000"
$StartDate
[1] "1/1/2001" "9/3/2003" "1/5/2004" "14/11/2007" "13/7/2015"
$Dept
[1] "IT" "HR" "Tech" "HR" "Sales"
To convert json file to a Data Frame, use the following:
jsondataframe <- as.data.frame(jsondata)
print(jsondataframe)
Output:
ID Name Salary StartDate Dept
1 1 Sam 32000 1/1/2001 IT
2 2 Rob 27000 9/3/2003 HR
3 3 Max 35000 1/5/2004 Tech
4 4 Robert 25000 14/11/2007 HR
5 5 Ivar 37000 13/7/2015 Sales