R语言 读取网络API的JSON数据

R语言 读取网络API的JSON数据

应用 编程 界面 允许用户使用某些功能,如创建、读取、更新和删除 CRUD 操作,而不需要直接暴露代码。这主要是以 J ava S cript O bject N otation的形式完成的,这是一种基于文本的格式,用于表示结构化数据。

在继续前进之前,我们应该了解基本的API调用。 CRUD 操作可以通过API的 POST、GET、PUT和DELETE 方法分别进行。当然,有些方法如PUT、POST和DELETE需要认证。在这篇文章中,我们将看到如何使用GET方法进行API调用以获取信息。

看一下这个API文档。它给出了关于一个词的信息,它的同义词,等等。如果你看一下这个URL,它给了我们关于geek 这个词的信息,是JSON格式的,看起来像这样。

使用R读取网络API的JSON数据

获取单词含义的字典API

从R中调用

为了用R编程语言的GET请求来调用这个URL,我们需要一个叫做 httr的 库,这个库并没有预装。所以请继续安装它。为了使用它的功能,在代码中包含这个库。

# Installing httr
install.packages("httr")
  
# including the library
library(httr)
R

现在,让我们用GET方法调用这个URL,并将其存储在 wordInfo 中。

# call the URL with the GET method
wordInfo <- GET("https://api.dictionaryapi.dev/api/v2/entries/en/geek")
R

GET函数也会返回一个包含所有服务器信息的列表。

使用R读取网络API的JSON数据

通过API获取的原始数据

为了得到其中的内容,我们需要使用 rawToChar 函数将其转换。但在这之前,要安装一个名为jsonlite的库来处理JSON格式。

# installing and loading jsonlite library
install.packages("jsonlite")
library(jsonlite)
  
rawToChar(wordInfo$content)
R

输出

使用R读取网络API的JSON数据

通过API获取的原始数据

现在我们得到了JSON格式的数据,为了使它更加干净和容易工作,我们将使用 fromJSON 函数。

# convert to cleaner format
data <- fromJSON(rawToChar(wordInfo$content))
R

输出

使用R读取网络API的JSON数据

使用fromJSON方法从JSON中获取数据到R

来提取其中的 含义

data$meanings
R

输出

使用R读取网络API的JSON数据

从JSON文件中提取的数据

它是一个列表,所以我们可以使用。

datameanings[[1]][[2]][[1]]definition
R

输出

'A carnival performer specializing in bizarre and unappetizing behavior.'
'A person who is intensely interested in a particular field or hobby 
 and often having limited or nonstandard social skills. Often used with 
 an attributive noun.'
'(by extension) An expert in a technical field, particularly one having
 to do with computers.''The subculture of geeks; an esoteric subject of
 interest that is marginal to the social mainstream; the philosophy, events,
 and physical artifacts of geeks; geekness.''An unfashionable or socially
 undesirable person.'
R

你也可以用弦乐演奏,做这样的事情。

library(httr)
library(jsonlite)
# storing search query in a variable
word <- "competition"
# appending the query at the end
wordInfo <- GET(paste("https://api.dictionaryapi.dev/api/v2/entries/en/", word))
  
data <- fromJSON(rawToChar(wordInfocontent))
  
datameanings[[1]][[2]][[1]]$definition
R

输出

'The action of competing.'
'A contest for a prize or award.'
'The competitors in such a contest.'
R

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册