0 votes
1 view
in R Programming by (5.2k 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 (25.3k points)

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

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...