update Valid to return false when there is additional data after the validated value

This commit is contained in:
Will Roden 2021-04-06 16:15:07 -05:00
parent a39bc30ed9
commit 4cae8f7bc7
2 changed files with 8 additions and 2 deletions

View File

@ -333,8 +333,13 @@ func HTMLEscape(dst *bytes.Buffer, src []byte) {
// Valid reports whether data is a valid JSON encoding. // Valid reports whether data is a valid JSON encoding.
func Valid(data []byte) bool { func Valid(data []byte) bool {
var v interface{} var v interface{}
if err := Unmarshal(data, &v); err != nil { decoder := NewDecoder(bytes.NewReader(data))
err := decoder.Decode(&v)
if err != nil {
return false return false
} }
return true if !decoder.More() {
return true
}
return decoder.InputOffset() >= int64(len(data))
} }

View File

@ -20,6 +20,7 @@ var validTests = []struct {
{`{}`, true}, {`{}`, true},
{`{"foo":"bar"}`, true}, {`{"foo":"bar"}`, true},
{`{"foo":"bar","bar":{"baz":["qux"]}}`, true}, {`{"foo":"bar","bar":{"baz":["qux"]}}`, true},
{`[""],`, false},
} }
func TestValid(t *testing.T) { func TestValid(t *testing.T) {