golang 报错:“unexpected end of JSON input” 如何解决?

寻技术 Html/CSS / JS脚本 2024年01月17日 71

近年来,Google开发并推出的go语言(也称为golang)已经成为许多开发者的选择之一。Golang以其快速的编译速度、高效的内存管理和强大的网络编程能力而被广泛应用。但在开发中,我们可能会遇到各种问题,例如在使用JSON解析库时,可能会遇到“unexpected end of JSON input”这个错误。

什么是“unexpected end of JSON input”错误?

这个错误会在正在解析JSON文本时,遇到文本末尾而未能正确地解析完整个JSON文本时触发。

在go语言中使用encoding/json包解析JSON。当我们把JSON转换成一个struct对象或map对象时,就可以使用json.Unmarshal方法解析。

例如,我们有这样一个HTTP响应消息:

HTTP/1.1 200 OK
Content-Type: application/json

{"code": 200, "message": "success", "data": {"name": "John", "age": 18}}

为了把这个JSON字符串转换成一个struct对象,我们可以这样做:

type Response struct {
    Code    int    `json:"code"`
    Message string `json:"message"`
    Data    struct {
        Name string `json:"name"`
        Age  int    `json:"age"`
    } `json:"data"`
}

...

resp, err := http.Get(url)
if err != nil {
    // handle error
}
defer resp.Body.Close()

var result Response
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(&result)
if err != nil {
    // handle error
}

在上面的示例中,我们通过http.Get从URL中获取HTTP响应,并把响应体中的JSON格式转换成一个Response struct对象。当JSON格式不正确时,会触发“unexpected end of JSON input”这个错误。

如何解决这个问题?

在处理JSON格式的时候,我们需要注意一些细节,例如JSON格式的正确性。在解析JSON文本时,可能会发现JSON格式不正确,例如缺少逗号、缺少引号或缺少括号等。如果我们使用json.Unmarshal方法,就必须确保JSON格式正确,否则会遇到“unexpected end of JSON input”这个错误。

在示例代码中,我们通过decoder.Decode(&result)把JSON格式的响应体解析成了一个Response结构体,但是如果响应体格式不正确,就会触发“unexpected end of JSON input”错误。

为了解决这个问题,我们应该对响应体的JSON格式进行验证。我们可以使用一些工具,如JSONLint,对JSON格式进行验证。如果JSON格式正确,就可以成功解析。如果JSON格式不正确,则需要修复JSON格式以正确解析响应体。

在实际编码中,我们可以采用如下做法,验证JSON格式:

resp, err := http.Get(url)
if err != nil {
    // handle error
}
defer resp.Body.Close()

result := make(map[string]interface{})
decoder := json.NewDecoder(resp.Body)
decoder.UseNumber() // 避免JSON数字溢出
err = decoder.Decode(&result)
if err != nil {
    // handle error
}

在上面的示例中,我们首先创建了一个空的map对象。然后我们通过json.NewDecoder方法获取一个decoder对象,并使用decoder.Decode方法解析响应体。我们还调用decoder.UseNumber方法,以避免JSON数字溢出。

当JSON格式不正确时,我们需要处理错误。我们可以使用如下代码处理错误:

respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
    // handle error
}

if err := json.Unmarshal(respBody, &result); err != nil {
    fmt.Println("JSON parse error:", err)
    return err
}

在上面的示例中,我们首先读取了响应体,并使用json.Unmarshal方法解析JSON文本。如果JSON格式不正确,则返回错误信息。

通过上述方法,我们可以避免“unexpected end of JSON input”错误的发生,确保我们的代码能够正确解析JSON格式。在实际开发中,我们还应该注意JSON格式的正确性和合法性,以确保我们的代码能够准确、高效地处理数据。

关闭

用微信“扫一扫”