Golang json Unmarshal" JSON输入的意外结束" [英] Golang json Unmarshal "unexpected end of JSON input"

查看:704
本文介绍了Golang json Unmarshal" JSON输入的意外结束"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一些代码来解析来自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输入在游乐场运行时没有错误。

代码不解码任何内容,因为结果字段未被导出。如果你导出结果字段:

pre $ $ $ $ $ $ $ $ $结果结构{
结果[] map [string] string

然后将输入解码为show n在这个操场示例中。



我怀疑你没有阅读应用程序中的整个响应主体。我建议使用以下代码解码JSON输入:

  err:= json.NewDecoder(resp.Body).Decode(& jsonData) 

解码器直接从响应正文读取。


I am working on some code to parse the JSON data from an HTTP response. The code I have looks something like this:

type ResultStruct struct {
    result []map[string]string
}

var jsonData ResultStruct
err = json.Unmarshal(respBytes, &jsonData)

The json in the respBytes variable looks like this:

{
 "result": [
  {
   "id": "ID 1"
  },
  {
   "id": "ID 2"
  }
 ]
}

However, 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?

Thanks in advance!

解决方案

The 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.

I ran the code with the example JSON input on the playground. It runs without error.

The code does not decode anything because the result field is not exported. If you export the result field:

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:

err := json.NewDecoder(resp.Body).Decode(&jsonData)

The decoder reads directly from the response body.

这篇关于Golang json Unmarshal" JSON输入的意外结束"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆