Golang json Unmarshal" JSON输入的意外结束" [英] Golang json Unmarshal "unexpected end of JSON input"
问题描述
我正在研究一些代码来解析来自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
不是零。当我打印出来时,它表示 JSON输入的意外结束
。这是什么造成的? JSON似乎有效。这个错误与我的自定义结构有什么关系?
预先感谢!
JSON输入的意外结束是语法错误(可能缺少
,
}
或]
)。错误不取决于您正在解码的值的类型。
我使用示例JSON输入在游乐场运行时没有错误。 代码不解码任何内容,因为 然后将输入解码为show n在这个操场示例中。 我怀疑你没有阅读应用程序中的整个响应主体。我建议使用以下代码解码JSON输入: 解码器直接从响应正文读取。 I am working on some code to parse the JSON data from an HTTP response. The code I have looks something like this: The json in the However, Thanks in advance! The I ran the code with the example JSON input on the playground. It runs without error. The code does not decode anything because the 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: The decoder reads directly from the response body. 这篇关于Golang json Unmarshal" JSON输入的意外结束"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
结果
字段未被导出。如果你导出结果字段:
pre $ $ $ $ $ $ $ $ $结果结构{
结果[] map [string] string
err:= json.NewDecoder(resp.Body).Decode(& jsonData)
type ResultStruct struct {
result []map[string]string
}
var jsonData ResultStruct
err = json.Unmarshal(respBytes, &jsonData)
respBytes
variable looks like this:{
"result": [
{
"id": "ID 1"
},
{
"id": "ID 2"
}
]
}
err
is 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?unexpected end of JSON input
is the result of a syntax error in the JSON input (likely a missing "
, }
, or ]
). The error does not depend on the type of the value that you are decoding to.result
field is not exported. If you export the result field:type ResultStruct struct {
Result []map[string]string
}
err := json.NewDecoder(resp.Body).Decode(&jsonData)