Golang json解组“JSON输入意外结束”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27994327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Golang json Unmarshal "unexpected end of JSON input"
提问by Stratus3D
I am working on some code to parse the JSON data from an HTTP response. The code I have looks something like this:
我正在编写一些代码来解析来自 HTTP 响应的 JSON 数据。我的代码看起来像这样:
type ResultStruct struct {
result []map[string]string
}
var jsonData ResultStruct
err = json.Unmarshal(respBytes, &jsonData)
The json in the respBytesvariable looks like this:
respBytes变量中的 json如下所示:
{
"result": [
{
"id": "ID 1"
},
{
"id": "ID 2"
}
]
}
However, erris not nil. When I print it out it says unexpected end of JSON input. What is causing this? The JSON seems to valid. Does this error have something to do with my custom struct?
然而,err也不是零。当我打印出来时,它说unexpected end of JSON input。这是什么原因造成的?JSON 似乎有效。这个错误是否与我的自定义结构有关?
Thanks in advance!
提前致谢!
采纳答案by Cerise Limón
The unexpected end of JSON inputis the result of a syntax errorin the JSON input (likely a missing ", }, or ]). The error does not depend on the type of the value that you are decoding to.
所述unexpected end of JSON input的结果是一个语法错误在JSON输入(可能丢失",}或])。该错误与您要解码为的值的类型无关。
I ran the code with the example JSON input on the playground. It runs without error.
我在操场上使用示例 JSON 输入运行代码。它运行没有错误。
The code does not decode anything because the resultfield is not exported. If you export the result field:
该代码不会解码任何内容,因为该result字段未导出。如果导出结果字段:
type ResultStruct struct {
Result []map[string]string
}
then the input is decoded as shown in this playground example.
然后输入被解码,如这个游乐场示例所示。
I suspect that you are not reading the entire response body in your application. I suggest decoding the JSON input using:
我怀疑您没有阅读应用程序中的整个响应正文。我建议使用以下方法解码 JSON 输入:
err := json.NewDecoder(resp.Body).Decode(&jsonData)
The decoder reads directly from the response body.
解码器直接从响应正文中读取。
回答by Robert
You can also get this error if you're using json.RawMessage in an unexported field. For example, the following code produces the same error:
如果您在未导出的字段中使用 json.RawMessage,您也会收到此错误。例如,以下代码会产生相同的错误:
package main
import (
"encoding/json"
"fmt"
)
type MyJson struct {
Foo bool `json:"foo"`
bar json.RawMessage `json:"bar"`
}
type Bar struct {
X int `json:"x"`
}
var respBytes = []byte(`
{
"foo": true,
"bar": { "x": 10 }
}`)
func main() {
var myJson MyJson
err := json.Unmarshal(respBytes, &myJson)
if err != nil {
fmt.Println(err)
return
}
myBar := new(Bar)
err = json.Unmarshal(myJson.bar, myBar)
fmt.Println(err)
}
If you export "MyJson.bar" field (e.g. -> "MyJson.Bar", then the code works.
如果您导出“MyJson.bar”字段(例如 ->“MyJson.Bar”,则代码有效。

