我正在编写一些代码来解析来自 HTTP 响应的 JSON 数据。我的代码看起来像这样:
type ResultStruct struct {
result []map[string]string
}
var jsonData ResultStruct
err = json.Unmarshal(respBytes, &jsonData)
respBytes
变量中的 json 如下所示:
{
"result": [
{
"id": "ID 1"
},
{
"id": "ID 2"
}
]
}
但是, err
不是零。当我打印出来时,上面写着 unexpected end of JSON input
。是什么原因造成的? JSON 似乎有效。这个错误与我的自定义结构有关吗?
提前致谢!
原文由 Stratus3D 发布,翻译遵循 CC BY-SA 4.0 许可协议
The
unexpected end of JSON input
is the result of a syntax error in the JSON input (likely a missing"
,}
, or]
).该错误不取决于您要解码的值的类型。我 在 playground 上 运行了带有示例 JSON 输入的代码。它运行没有错误。
该代码不解码任何内容,因为
result
字段未导出。如果导出结果字段:然后输入被解码,如 playground example 所示。
我怀疑您没有阅读应用程序中的整个响应主体。我建议使用以下方法解码 JSON 输入:
解码器直接从响应体中读取。