错误:模型 : invalid character '<' looking for beginning of value

2026年04月22日 15:08 processing

错误信息

错误:模型 : invalid character '<' looking for beginning of value

AI 解决方案

##报错分析

1. 错误翻译


原文:invalid character '<' looking for beginning of value
译文:在寻找值的开头时发现了无效字符‘<’

2. 原因分析


  • 根本原因:程序尝试解析JSON时,实际获取的内容包含<(通常是API返回HTML错误页而非JSON)。

  • 发生位置:JSON解析逻辑处(如json.UnmarshalJSON.parse等)。
  • 3. 解决方案


    以Python为例(先校验类型+异常捕获):
    import requests
    import json
    
    url = "你的API地址"
    resp = requests.get(url)
    
    # 1. 检查响应类型
    if "application/json" not in resp.headers.get("Content-Type", ""):
        print(f"非JSON响应: {resp.text}")
    else:
        # 2. 安全解析
        try:
            data = resp.json()
            print("解析成功:", data)
        except json.JSONDecodeError as e:
            print(f"JSON解析失败: {e},原始内容: {resp.text}")
    

    以Go为例:

    package main
    
    import (
    	"encoding/json"
    	"fmt"
    	"io/ioutil"
    	"net/http"
    )
    
    func main() {
    	resp, _ := http.Get("你的API地址")
    	defer resp.Body.Close()
    	body, _ := ioutil.ReadAll(resp.Body)
    
    	// 校验Content-Type
    	if resp.Header.Get("Content-Type") != "application/json" {
    		fmt.Printf("非JSON响应: %s\n", body)
    		return
    	}
    
    	var data map[string]interface{}
    	if err := json.Unmarshal(body, &data); err != nil {
    		fmt.Printf("JSON解析失败: %v,原始内容: %s\n", err, body)
    		return
    	}
    	fmt.Println("解析成功:", data)
    }
    

    4. 预防措施


  • 最佳实践1:解析前强制验证响应Content-Typeapplication/json

  • 最佳实践2:用异常处理捕获解析错误,打印原始响应内容定位问题。

  • 推荐工具:Postman(测试接口返回)、curl(查看原始响应)。