Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read data from a JSON object(in a file) into R?

Tags:

json

r

I am new to R and do not have much exposure to programming. I am having a problem loading a file(contains JSON object) into R.

> library(rjson)
> jsonFile <- "C:\\Users\\jsonRecords.txt"
> jsonData <- fromJSON( jsonFile, method = "C", unexpected.escape = "error" )
Error in fromJSON(jsonFile, method = "C", unexpected.escape = "error") : 
  unexpected character 'C'

I wanted the data to be read into R for further analysis.. Any help will be appreciated.

Thanks

like image 446
user1946217 Avatar asked Feb 26 '13 06:02

user1946217


People also ask

Which function is used to read a JSON file in R?

Reading the JSON file in R is a very easy and effective process. R provide from JSON() function to extract data from a JSON file. This function, by default, extracts the data in the form of a list. This function takes the JSON file and returns the records which are contained in it.

How do I view data in a JSON file?

Cross-platform to open JSON files: Generally, users can open the JSON file in any text editor as it is a plain text-based file. The Google Chrome and Mozilla Firefox web browsers are cross-platform to open JSON files that are compatible with every operating system (OS).

How do I read a JSON file into a DataFrame?

Reading JSON Files using Pandas To read the files, we use read_json() function and through it, we pass the path to the JSON file we want to read. Once we do that, it returns a “DataFrame”( A table of rows and columns) that stores data.


1 Answers

Try just this:

    fromJSON( file = json_file )

It will read all the file. here an example:

write(toJSON( iris ),'jstest')
res <- fromJSON( file="jstest")

str(res)
List of 5
 $ Sepal.Length: num [1:150] 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
 $ Sepal.Width : num [1:150] 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
 $ Petal.Length: num [1:150] 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
 $ Petal.Width : num [1:150] 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
 $ Species     : chr [1:150] "setosa" "setosa" "setosa" "setosa" ...
like image 66
agstudy Avatar answered Nov 09 '22 15:11

agstudy