英文:
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
不为 nil。当我打印它时,显示出现了 unexpected end of JSON input
错误。这是什么原因造成的?JSON 数据似乎是有效的。这个错误与我的自定义结构有关吗?
提前感谢!
英文:
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!
答案1
得分: 25
unexpected end of JSON input
是 JSON 输入中的语法错误(可能是缺少了 "
、}
或 ]
)的结果。这个错误与你解码的值的类型无关。
我在 playground 上运行了这段代码,没有出现错误。
这段代码没有解码任何内容,因为 result
字段没有被导出。如果你导出 result
字段:
type ResultStruct struct {
Result []map[string]string
}
那么输入将会被解码,就像这个 playground 示例 中所示。
我怀疑你在应用程序中没有完整地读取响应体。我建议使用以下代码解码 JSON 输入:
err := json.NewDecoder(resp.Body).Decode(&jsonData)
解码器直接从响应体中读取数据。
英文:
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.
答案2
得分: 6
你也可能因为在一个未导出的字段中使用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)
}
如果你导出 "MyJson.bar" 字段(例如,改为 "MyJson.Bar"),那么代码就可以正常工作。
英文:
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:
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.
答案3
得分: 1
这里不是这种情况;但是如果你在从文件加载JSON时遇到这个错误,那么可能是因为缓冲区的字节切片没有初始化为文件的字节大小。[像我这样的新手经常会遇到这种情况!] 由于这是我找到的第一个搜索结果,所以还需要一些挖掘才能弄清楚。在这种情况下,错误信息有点误导性。
type GenesisResultStruct []GenesisField
fileinfo, _ := genesis.Stat()
bs := make([]byte, fileinfo.Size())
//bs := []byte {} // 错误!!
_, error := genesis.Read(bs)
if error != nil {
fmt.Println("genesis read error: ", error)
os.Exit(1)
}
var jsonData GenesisResultStruct
eGen = json.Unmarshal(bs, &jsonData)
if eGen != nil {
fmt.Println("genesis unmarshal error: ", eGen)
os.Exit(1)
}
英文:
it is not the case here; but if you are getting this error loading json from a file it Will occur if the byte slice for the buffer is not initialized the the byte size of the file. [when you're new like me that happens! ] Since this is the first search result I got it still took some digging to figure out. In this use case the error is a bit misleading.
type GenesisResultStruct []GenesisField
fileinfo, _ := genesis.Stat()
bs := make([]byte, fileinfo.Size())
//bs := []byte {} // wrong!!
_, error := genesis.Read(bs)
if error != nil {
fmt.Println("genesis read error: ", error)
os.Exit(1)
}
var jsonData GenesisResultStruct
eGen = json.Unmarshal(bs, &jsonData)
if eGen != nil {
fmt.Println("genesis unmarshal error: ", eGen)
os.Exit(1)
}
答案4
得分: 0
今天遇到了同样的问题。
如果 respBytes
是 nil
,或者在将其解组为切片时没有方括号 []
,也会出现这个错误。在这种情况下,你需要显式地设置 respBytes
。
由于你将其解组为切片,所以字节切片中应该有方括号 []
。
if src == nil {
src = []byte("[]")
}
英文:
Faced the same issue today.
You can also get this error if the respBytes
is nil
or there are no brackets []
if you are unmarshalling it to a slice.
In that case, you need to explicitly set respBytes
.
As you are unmarshalling it to a slice, brackets []
are expected in the byte-slice
if src == nil {
src = []byte("[]")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论