我正在尝试从 R 脚本中的 API 调用访问 JSON 响应。API调用成功,我可以在控制台中查看JSON响应。但是,我无法从中访问任何数据。
示例代码段是:
require(httr)
target <- '#trump'
sentence<- 'Donald trump has a wonderful toupe, it really is quite stunning that a man can be so refined and elegant'
query <- url_encode(sentence)
target <- gsub('#', '', target)
endpoint <- "https://alchemy.p.mashape.com/text/TextGetTargetedSentiment?outputMode=json&target="
apiCall <- paste(endpoint, target, '&text=', query, sep = '')
resp <-GET(apiCall, add_headers("X-Mashape-Key" = sentimentKey, "Accept" = "application/json"))
stop_for_status(resp)
headers(resp)
str(content(resp))
content(resp, "text")
Run Code Online (Sandbox Code Playgroud)
我遵循了 CRAN(此处)的 httr 快速入门指南以及此堆栈中的示例。
不幸的是,我不断收到“content() 中未使用的参数‘文本’”或“不存在接受一类‘响应’的 content() 定义。有人有什么建议吗?PS 标题将打印,resp$content 将打印原始比特流
扩展注释,您需要在对 的调用中显式设置内容类型content(...)。由于您的代码不可重现,因此以下是使用人口普查局地理编码器(返回 json 响应)的示例。
library(httr)
url <- "http://geocoding.geo.census.gov/geocoder/locations/onelineaddress"
resp <-GET(url, query=list(address="1600 Pennsylvania Avenue, Washington DC",
benchmark=9,
format="json"))
json <- content(resp, type="application/json")
json$result$addressMatches[[1]]$coordinates
# $x
# [1] -77.038025
#
# $y
# [1] 38.898735
Run Code Online (Sandbox Code Playgroud)
假设您实际上得到了一个 json 响应,并且它的格式良好,只需使用content(resp, type="application/json")就可以了。
| 归档时间: |
|
| 查看次数: |
1743 次 |
| 最近记录: |