Golang json Unmarshal "unexpected end to JSON input"

I am working on some code to parse 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) 

json in respBytes variable looks like this:

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

However, err not equal to zero. When I print it, it says unexpected end of JSON input . What caused this? It seems that JSON is valid. Does this error have anything to do with my custom structure?

Thanks in advance!

+11
json go unmarshalling
source share
2 answers

unexpected end of JSON input is the result of a syntax error in the JSON input (probably missing " , } or ] ). The error does not depend on the type of value you are decoding.

I ran the code with an example of JSON input on the playground . It works without errors.

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 example of a playground .

I suspect that you are not reading the entire response organ in your application. I suggest decoding JSON input using:

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

The decoder reads directly from the response body.

+5
source share

You can also get this error if you use json.RawMessage in an unallocated field. For example, the following code generates 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 the field "MyJson.bar" (for example, β†’ "MyJson.Bar", then the code works.

+2
source share

All Articles