R JSON File
JSON: JavaScript Object NJSON (JavaScript Object Notation).
JSON is a syntax for storing and exchanging text information.
JSON is similar to XML, but it is smaller, faster, and easier to parse than XML.
If you are not familiar with JSON yet, you can first refer to:JSON Tutorial
To read and write JSON files in R, you need to install an extension package. You can install it by entering the following command in the R console:
install.packages("rjson", repos = "https://mirrors.ustc.edu.cn/CRAN/")
Check whether the installation is successful:
> any(grepl("rjson",installed.packages()))
[1] TRUE
Create a sites.json file. The JSON file should be in the same directory as the test script. The code is as follows:
Example
To view data, use for a certain row[ ], use for the specified rows and columns[[ ]]:
Example
library("rjson")
# Get JSON data
result <- fromJSON(file = "sites.json")
# Output the result
print(result)
print("===============")
# Output the result of the 1st column
print(result[1])
print("===============")
# Output the result of the 2nd row and 2nd column
print(result[[2]][[2]])
Executing the above code produces the following output:
$id [1] "1" "2" "3" $name [1] "Google" "Example" "Taobao" $url [1] "www.google.com" "www.example.com" "www.taobao.com" $likes [1] 111 222 333 [1] "===============" $id [1] "1" "2" "3" [1] "===============" [1] "Example"
We can also useas.data.frame()function to convert the JSON file data to a data frame type, making it more convenient for us to manipulate the data:
Example
library("rjson")
# Get JSON data
result <- fromJSON(file = "sites.json")
# Convert to a data frame
json_data_frame <- as.data.frame(result)
print(json_data_frame)
Executing the above code produces the following output:
id name url likes 1 1 Google www.google.com 111 2 2 Example www.example.com 222 3 3 Taobao www.taobao.com 333Other extensions