Merge pull request #177 from WillAbides/valid

Make Valid more consistent with "encoding/json"
This commit is contained in:
Masaaki Goshima 2021-04-10 15:47:52 +09:00 committed by GitHub
commit 8bc5727ba4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
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.
func Valid(data []byte) bool {
var v interface{}
if err := Unmarshal(data, &v); err != nil {
decoder := NewDecoder(bytes.NewReader(data))
err := decoder.Decode(&v)
if err != nil {
return false
}
if !decoder.More() {
return true
}
return decoder.InputOffset() >= int64(len(data))
}

View File

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