Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (7.3k points)

Is there a way to import data from a JSON file into R? More specifically, the file is an array of JSON objects with string fields, objects, and arrays. The RJSON Package isn't very clear on how to deal with this http://cran.r-project.org/web/packages/rjson/rjson.pdf.

1 Answer

0 votes
by

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

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...