How to Fix Error: unexpected end of JSON input in Go

The Error: unexpected end of json input occurs when the “JSON being parsed is either empty or truncated.”

To fix the Error: unexpected end of json input in Go, ensure the JSON input is complete and well-formed.

package main

import (

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)
  fmt.Printf("Person: %+v\n", s)


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")

That’s it!

Related posts

json: cannot unmarshal object into Go struct field

Lowercase JSON Key Names with JSON Marshal in Go