From 4cae8f7bc7a3294312a23445018e085d1de66abb Mon Sep 17 00:00:00 2001 From: Will Roden Date: Tue, 6 Apr 2021 16:15:07 -0500 Subject: [PATCH] update Valid to return false when there is additional data after the validated value --- json.go | 9 +++++++-- json_test.go | 1 + 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/json.go b/json.go index 3d879d0..05756ef 100644 --- a/json.go +++ b/json.go @@ -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 } - return true + if !decoder.More() { + return true + } + return decoder.InputOffset() >= int64(len(data)) } diff --git a/json_test.go b/json_test.go index a73db50..9470ed1 100644 --- a/json_test.go +++ b/json_test.go @@ -20,6 +20,7 @@ var validTests = []struct { {`{}`, true}, {`{"foo":"bar"}`, true}, {`{"foo":"bar","bar":{"baz":["qux"]}}`, true}, + {`[""],`, false}, } func TestValid(t *testing.T) {