From: Matt Layher Date: Tue, 13 Dec 2016 22:57:06 +0000 (-0500) Subject: encoding/json: add Valid for checking validity of input bytes X-Git-Tag: go1.9beta1~1687 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=3f7a35d91c7079269dec5cefef7599148f0279e0;p=gostls13.git encoding/json: add Valid for checking validity of input bytes Fixes #18086 Change-Id: Idc501dd37893e04a01c6ed9920147d24c0c1fa18 Reviewed-on: https://go-review.googlesource.com/34202 Reviewed-by: Brad Fitzpatrick Run-TryBot: Brad Fitzpatrick TryBot-Result: Gobot Gobot --- diff --git a/src/encoding/json/scanner.go b/src/encoding/json/scanner.go index a6d8706c73..ae34418d1d 100644 --- a/src/encoding/json/scanner.go +++ b/src/encoding/json/scanner.go @@ -15,6 +15,11 @@ package json import "strconv" +// Valid reports whether data is a valid JSON encoding. +func Valid(data []byte) bool { + return checkValid(data, &scanner{}) == nil +} + // checkValid verifies that data is valid JSON-encoded data. // scan is passed in for use by checkValid to avoid an allocation. func checkValid(data []byte, scan *scanner) error { diff --git a/src/encoding/json/scanner_test.go b/src/encoding/json/scanner_test.go index c5c1be31f1..0d4518a632 100644 --- a/src/encoding/json/scanner_test.go +++ b/src/encoding/json/scanner_test.go @@ -12,6 +12,26 @@ import ( "testing" ) +var validTests = []struct { + data string + ok bool +}{ + {`foo`, false}, + {`}{`, false}, + {`{]`, false}, + {`{}`, true}, + {`{"foo":"bar"}`, true}, + {`{"foo":"bar","bar":{"baz":["qux"]}}`, true}, +} + +func TestValid(t *testing.T) { + for _, tt := range validTests { + if ok := Valid([]byte(tt.data)); ok != tt.ok { + t.Errorf("Valid(%#q) = %v, want %v", tt.data, ok, tt.ok) + } + } +} + // Tests of simple examples. type example struct {