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

含换行符的JSON数据导致Go中json.Unmarshal解析失败

问题原因与解决办法

你的代码解析失败的核心原因是JSON字符串不符合标准JSON规范:字符串值中包含了未转义的换行符,而标准JSON要求字符串里的换行必须用\n转义。同时你没有处理json.Unmarshal的返回错误,所以无法直接看到解析失败的原因,才会得到空结构体。

解决方式

方式一:修正原始JSON字符串(推荐)

将字符串中的换行转义,或者直接去掉换行合并成一行:

package main

import (
    "encoding/json"
    "fmt"
)

type response struct {
    Data1 string `json:"data1"`
    Data2 string `json:"data2"`
}

func main() {
    // 转义换行符
    str := `{"data1": "this is \ntest data 1", "data2": "this is test data 2"}`
    // 或者直接合并成一行
    // str := `{"data1": "this is test data 1", "data2": "this is test data 2"}`

    res := response{}
    fmt.Println("json string is \n")
    fmt.Println(str)

    // 必须检查解析错误
    err := json.Unmarshal([]byte(str), &res)
    if err != nil {
        fmt.Println("解析错误:", err)
        return
    }

    fmt.Println("structure output is \n")
    fmt.Println(res)
}

方式二:使用非严格模式解析(无法修改原始JSON时)

如果无法修改原始JSON字符串,可以使用json.Decoder并关闭严格模式,允许解析包含未转义换行的非标准JSON:

package main

import (
    "encoding/json"
    "fmt"
    "strings"
)

type response struct {
    Data1 string `json:"data1"`
    Data2 string `json:"data2"`
}

func main() {
    str := `{"data1": "this is 
    test data 1", 
    "data2": "this is test data 2"}`

    res := response{}
    fmt.Println("json string is \n")
    fmt.Println(str)

    decoder := json.NewDecoder(strings.NewReader(str))
    decoder.Strict = false // 关闭严格模式,允许非标准JSON格式
    err := decoder.Decode(&res)
    if err != nil {
        fmt.Println("解析错误:", err)
        return
    }

    fmt.Println("structure output is \n")
    fmt.Println(res)
}

关键提醒

任何JSON解析操作都必须检查返回的错误,这能帮你快速定位问题,比如原始代码中添加错误检查后,会得到明确的错误提示:invalid character '\n' in string literal。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 07:27:24