English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
JSON: JavaScript Object Notation(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.
If you are not familiar with JSON, you can first refer to:JSON Tutorial
To install the R JSON extension package, we can enter the following command in the R console:
install.packages("rjson", repositories = "https://mirrors.ustc.edu.cn/CRAN/")
Check if the installation is successful:
any(grepl("rjson",installed.packages())) [1]] TRUE
Create a sites.json file, the json file is in the same directory as the test script, the code is as follows:
{ "id":["1"2"3"] "name":["Google","w3codebox","Taobao"], "url":["www.google.com","www.3codebox.com","www.taobao.com"], "likes":[ 111,222,333] }
Next, we can use the rjson package to load the data from the json file.
To view the data, use [ ] for a specific row, and use [[ ]] for a specific row and column:
# Load rjson package library("rjson") # Get json data result <- fromJSON(file = "sites.json") # Output the result print(result) print("===============") # Output the 1 Column results print(result[1]) print("===============") # Output the 2 Row 2 Column results print(result[[2]]2]])
The output of the above code is:
$id [1] "1" "2" "3" $name [1] "Google" "w3codebox" "Taobao" $url [1] "www.google.com" "www.oldtoolbag.com" "www.taobao.com" $likes [1] 111 222 333 [1] "===============" $id [1] "1" "2" "3" [1] "===============" [1] "w3codebox"
We can also use as.data.frame() The function can convert json file data to data frame type, which makes it easier to operate on the data:
# Load rjson package library("rjson") # Get json data result <- fromJSON(file = "sites.json") # Convert to data frame json_data_frame <- as.data.frame(result) print(json_data_frame)
The output of the above code is:
id name url likes 1 1 Google www.google.com 111 2 2 w3codebox www.oldtoolbag.com 222 3 3 Taobao www.taobao.com 333