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

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 (

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 for today.

Leave a Comment