R JSON 文件

JSON: JavaScript Object Notation(JavaScript 對象表示法)。

JSON 是存儲和交換文本信息的語法。

JSON 類似 XML,但比 XML 更小、更快,更易解析。

如果你對 JSON 還不了解,可以先查閱:JSON 教程

R 語言讀寫 JSON 文件需要安裝擴(kuò)展包,我們可以在 R 到控制臺輸入以下命令來安裝:

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

查看是否安裝成功:

> any(grepl("rjson",installed.packages()))
[1] TRUE

創(chuàng)建 sites.json 文件,json 文件與測試腳本同一目錄下,代碼如下:

{ 
   "id":["1","2","3"],
   "name":["Google","Nhooo","Taobao"],
   "url":["www.google.com","www.soo66.com","www.taobao.com"],
   "likes":[ 111,222,333]
}

接下來我們可以使用 rjson 包來載入 json 文件的數(shù)據(jù)。

查看數(shù)據(jù),某一行使用 [ ], 指定的行和列使用 [[ ]]:

# 載入 rjson 包
library("rjson")

# 獲取 json 數(shù)據(jù)
result <- fromJSON(file = "sites.json")

# 輸出結(jié)果
print(result)

print("===============")

# 輸出第 1 列的結(jié)果
print(result[1])

print("===============")
# 輸出第 2 行第 2 列的結(jié)果
print(result[[2]][[2]])

執(zhí)行以上代碼輸出結(jié)果為:

$id
[1] "1" "2" "3"
$name
[1] "Google" "Nhooo" "Taobao"
$url
[1] "www.google.com" "www.soo66.com" "www.taobao.com"
$likes
[1] 111 222 333
[1] "==============="
$id
[1] "1" "2" "3"
[1] "==============="
[1] "Nhooo"

我們也可以使用 as.data.frame() 函數(shù)將 json 文件數(shù)據(jù)可以轉(zhuǎn)為數(shù)據(jù)框類型,這樣我們就更方便對數(shù)據(jù)進(jìn)行操作:

# 載入 rjson 包
library("rjson")

# 獲取 json 數(shù)據(jù)
result <- fromJSON(file = "sites.json")

# 轉(zhuǎn)為數(shù)據(jù)框
json_data_frame <- as.data.frame(result)

print(json_data_frame)

執(zhí)行以上代碼輸出結(jié)果為:

  id   name            url likes
1  1 Google www.google.com   111
2  2 Nhooo www.soo66.com   222
3  3 Taobao www.taobao.com   333
丰满人妻一级特黄a大片,午夜无码免费福利一级,欧美亚洲精品在线,国产婷婷成人久久Av免费高清