To fix the Error: unexpected end of json input in Go, ensure the JSON input is complete and well-formed.
Golang raises the Error: unexpected end of json input when you try to unmarshal a JSON string using the json.Unmarshal() function, but the input JSON is incomplete, malformed, or empty.
package main
import (
"encoding/json"
"fmt"
)
type Student struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
var s Student
jsonData := `{"name":"Krunal", "age": 30`
err := json.Unmarshal([]byte(jsonData), &s)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Printf("Person: %+v\n", s)
}
Output
Error: unexpected end of JSON input
In this example, the jsonData variable contains an incomplete JSON string (missing the closing }), which would result in the “unexpected end of JSON input” error.
You can fix the error by correcting the JSON input.
jsonData := `{"name":"Krunal", "age": 30}`
In a real-world scenario, the JSON input might come from an external source like a file or an API response.
You should always validate the JSON input before attempting to unmarshal it.
If you presume the JSON input might be empty, you can add a check before calling the json.Unmarshal() function.
if len(jsonData) == 0 {
fmt.Println("Error: Empty JSON input")
return
}
That’s it for today.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Distributed and cloud computing and is an expert in Go Language.