Last active
December 19, 2015 05:39
-
-
Save titanous/5906010 to your computer and use it in GitHub Desktop.
Pretty JSON syntax errors in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"encoding/json" | |
"io" | |
"strconv" | |
) | |
type JSONSyntaxError struct { | |
Msg string | |
Line []byte | |
LineNo int | |
CharNo int | |
} | |
func (e *JSONSyntaxError) Error() string { | |
return e.Msg + " at line " + strconv.Itoa(e.LineNo) + ", char " + strconv.Itoa(e.CharNo) + "." | |
} | |
func newJSONSyntaxError(err *json.SyntaxError, data []byte) *JSONSyntaxError { | |
newline := []byte{'\n'} | |
start := bytes.LastIndex(data[:err.Offset], newline) + 1 | |
end := len(data) | |
if idx := bytes.Index(data[start:], newline); idx >= 0 { | |
end = start + idx | |
} | |
return &JSONSyntaxError{ | |
LineNo: bytes.Count(data[:start], newline) + 1, | |
CharNo: int(err.Offset) - start - 1, | |
Line: append([]byte{}, data[start:end]...), | |
Msg: err.Error(), | |
} | |
} | |
func DecodeJSON(data io.Reader, dest interface{}) error { | |
buf := &bytes.Buffer{} | |
err := json.NewDecoder(io.TeeReader(data, buf)).Decode(dest) | |
if syntaxErr, ok := err.(*json.SyntaxError); ok { | |
return newJSONSyntaxError(syntaxErr, buf.Bytes()) | |
} | |
return err | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment