在读取API数据后,使用utf8::utf8_decode()
函数将数据转换为UTF-8编码,并使用stringi::stri_enc_toascii()
函数将字符编码转换为ASCII,示例如下:
library(httr)
library(jsonlite)
library(utf8)
library(stringi)
response <- GET("https://example.com/api/data") # 示例API
data <- content(response, as = "text")
data_utf8 <- utf8_decode(data)
data_ascii <- stri_enc_toascii(data_utf8)
data_json <- fromJSON(data_ascii)
上述代码首先使用httr
库获取API数据,然后将返回的数据转换为UTF-8编码并转换为ASCII编码,最后使用jsonlite
库将JSON格式的数据转换为R中的数据结构。
这样代码中的字符就可以正常显示了。
上一篇:API数据在函数外被访问