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

使用httr::GET请求后jsonlite::fromJson报错的原因及解决咨询

解决httr::GET响应传入jsonlite::fromJson时的报错问题

问题场景

执行httr::GET请求后得到状态码200的响应(Content-Type为application/json; charset=utf-8),但直接将响应对象传入jsonlite::fromJson时触发错误:

Error: Argument 'txt' must be a JSON string, URL or file.

报错原因

httr::GET返回的是httr响应对象,包含响应头、状态码、原始内容等元数据,并非纯JSON字符串。而jsonlite::fromJson仅接受JSON字符串、URL或本地文件路径作为输入,无法直接识别响应对象。

无需额外步骤的解决思路

  1. 直接用httr内置函数解析(推荐)
    httr的content()函数会自动识别响应的Content-Type,直接返回解析后的R对象(列表或数据框),无需手动处理JSON字符串:

    response <- httr::GET("your_api_url")
    parsed_data <- httr::content(response, "parsed")
    
  2. 若坚持用jsonlite解析
    先通过content()提取纯JSON字符串,再传入jsonlite::fromJson:

    response <- httr::GET("your_api_url")
    json_str <- httr::content(response, "text")
    parsed_data <- jsonlite::fromJson(json_str)
    

额外验证点

确保接口返回的JSON内容是完整结构(你提供的响应片段中JSON未闭合,实际请求需确认接口返回完整有效的JSON,否则解析仍会失败)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 11:31:35