You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R调用NASA POWER API解析JSON偶发invalid character错误如何解决

问题原因及修复方案

1. 部分经纬度请求返回HTML的原因

  • 高频请求限流:NASA POWER API存在单位时间请求频次限制,短时间内发送多个相似请求会触发限流规则,服务端会返回HTML格式的错误提示页,且HTTP状态码仍显示为200,不会返回4xx/5xx错误码,这和你猜测的原因一致。
  • 参数触发服务端异常:部分坐标点若落在无有效气象数据的区域,或者请求的时间跨度过大、请求变量过多超过单次查询上限时,服务端未做标准化JSON错误返回,直接输出了HTML错误页面。

2. R中Response类型的解析修正方案

你需要在解析前新增返回内容校验逻辑,同时优化原有解析写法避免编码错误,修正后的完整流程如下:

library(httr)
library(jsonlite)
library(tibble)

# 构造API请求URL
api_url <- "https://power.larc.nasa.gov/beta/api/temporal/hourly/point?start=20080101&end=20180101&latitude=-6.280&longitude=39.288&community=re&parameters=ALLSKY_SFC_SW_DWN,T2M,WS2M&format=json&user=dataqueryabed&header=false&time-standard=lst"

# 发送请求
response_given <- GET(api_url)

# 校验返回内容类型,仅JSON格式走解析逻辑
if (grepl("application/json", headers(response_given)$`content-type`)) {
  # 直接用content函数读取文本,避免rawToChar的编码问题
  response_json <- content(response_given, as = "text", encoding = "UTF-8")
  some_response_unframed <- fromJSON(response_json)
  response_framed <- enframe(unlist(some_response_unframed))
} else {
  # 非JSON返回时执行重试逻辑,最多重试3次,每次间隔5秒冷却
  max_retry <- 3
  retry_count <- 0
  parse_success <- FALSE
  while (retry_count < max_retry && !parse_success) {
    Sys.sleep(5)
    retry_resp <- GET(api_url)
    if (grepl("application/json", headers(retry_resp)$`content-type`)) {
      response_json <- content(retry_resp, as = "text", encoding = "UTF-8")
      some_response_unframed <- fromJSON(response_json)
      response_framed <- enframe(unlist(some_response_unframed))
      parse_success <- TRUE
    }
    retry_count <- retry_count + 1
  }
  # 重试失败抛出明确错误
  if (!parse_success) {
    stop("多次重试仍未获取有效数据,请检查请求参数或稍后再试")
  }
}

额外优化建议

  • 单次请求的时间跨度不要超过5年,拆分长周期查询为多个短请求可以大幅降低触发限流的概率。
  • 若需要排查具体错误,可以在返回非JSON时打印返回内容:print(content(response_given, as = "text")),确认是限流还是参数错误。

内容的提问来源于stack exchange,提问作者Abed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 12:15:04