Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R JSON Files

R JSON Files

JSON: JavaScript Object Notation (JavaScript Object Notation).

JSON is a syntax for storing and exchanging text information.

JSON is similar to XML, but smaller, faster, and easier to parse than XML.

If you are not yet familiar with JSON, you can first refer to:JSON Tutorial

Reading and writing JSON files in R requires installing an extension package; we can enter the following command in the R console to install it:

install.packages("rjson", repos = "https://mirrors.ustc.edu.cn/CRAN/")

Check whether it was installed successfully:

> any(grepl("rjson",installed.packages()))

[1] TRUE

Create a sites.json file in the same directory as the test script, with the following code:

Example

{

"

id

"

:

[

"

1

"

,

"

2

"

,

"

3

"

]

,

"

name

"

:

[

"

Google

"

,

"

Runoob

"

,

"

Taobao

"

]

,

"

url

"

:

[

"

www.google.com

"

,

"

www.runoob.com

"

,

"

www.taobao.com

"

]

,

"

likes

"

:

[

111

,

222

,

333

]

}

Next we can use the rjson package to load data from the json file.

To view data, use [ ] for a single row and [[ ]] for a specified row and column:

Example

Load the rjson package

library

(

"rjson"

)

Get the json data

result

<-

fromJSON

(

file

=

"sites.json"

)

Output result

print

(

result

)

print

(

"==============="

)

Output the result of the 1st column

print

(

result

[

1

]

)

print

(

"==============="

)

Output the result of the 2nd row, 2nd column

print

(

result

[

[

2

]

]

[

[

2

]

]

)

The output of the code above is:

$id

[1] "1" "2" "3"



$name

[1] "Google" "Runoob" "Taobao"



$url

[1] "www.google.com" "www.runoob.com" "www.taobao.com"



$likes

[1] 111 222 333



[1] "==============="

$id

[1] "1" "2" "3"



[1] "==============="

[1] "Runoob"

We can also use the as.data.frame() The function can convert json file data into a data frame type, making it more convenient to operate on the data:

Example

Load the rjson package

library

(

"rjson"

)

Get the json data

result

<-

fromJSON

(

file

=

"sites.json"

)

Convert to a data frame

json_data_frame

<-

as.data.frame

(

result

)

print

(

json_data_frame

)

The output of the code above is:



  id   name            url likes

1  1 Google www.google.com   111

2  2 Runoob www.runoob.com   222

3  3 Taobao www.taobao.com   333