Golang: How to check that a JSON is invalid and describe where is the issue?

Following is an example that I hope helps you out.

func validateJSON(value string) error {
	var js json.RawMessage
	byteValue := []byte(value)
	if err := json.Unmarshal(byteValue, &js); err != nil {
		switch t := err.(type) {
		case *json.SyntaxError:
			jsn := string(byteValue[0:t.Offset])
			jsn += "<--(see the invalid character)"
			return fmt.Errorf("invalid character at %v\n %s", t.Offset, jsn)
		case *json.UnmarshalTypeError:
			jsn := string(byteValue[0:t.Offset])
			jsn += "<--(see the invalid type)"
			return fmt.Errorf("invalid value at %v\n %s", t.Offset, jsn)
		default:
			return err
		}
	}
	return nil
}

See:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s