How to Validate JSON in Go

Validate JSON in Go by using json.Unmarshal and checking the returned error to ensure the data is well-formed.

Use the encoding/json package's json.Unmarshal function to validate JSON by attempting to decode it into a variable and checking for errors. If the JSON is invalid, the function returns a non-nil error.

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	data := []byte(`{"key": "value"}`)
	var result map[string]interface{}
	if err := json.Unmarshal(data, &result); err != nil {
		fmt.Println("Invalid JSON:", err)
		return
	}
	fmt.Println("Valid JSON")
}