diff options
| author | Matt Layher <mdlayher@gmail.com> | 2016-12-13 17:57:06 -0500 |
|---|---|---|
| committer | Brad Fitzpatrick <bradfitz@golang.org> | 2017-02-07 23:48:44 +0000 |
| commit | 3f7a35d91c7079269dec5cefef7599148f0279e0 (patch) | |
| tree | 90cbbe099c2a47ced57ada09c5789e1c3480592f /src/encoding/json | |
| parent | 1f93ba66d6ccb200e8b0a037a01265f6563fdf58 (diff) | |
| download | go-3f7a35d91c7079269dec5cefef7599148f0279e0.tar.xz | |
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 <bradfitz@golang.org>
Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Diffstat (limited to 'src/encoding/json')
| -rw-r--r-- | src/encoding/json/scanner.go | 5 | ||||
| -rw-r--r-- | src/encoding/json/scanner_test.go | 20 |
2 files changed, 25 insertions, 0 deletions
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 { |
