]> Cypherpunks repositories - gostls13.git/commitdiff
encoding/json: add Valid for checking validity of input bytes
authorMatt Layher <mdlayher@gmail.com>
Tue, 13 Dec 2016 22:57:06 +0000 (17:57 -0500)
committerBrad Fitzpatrick <bradfitz@golang.org>
Tue, 7 Feb 2017 23:48:44 +0000 (23:48 +0000)
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>

src/encoding/json/scanner.go
src/encoding/json/scanner_test.go

index a6d8706c73130dcb55c190d7cae251d7f0e6c7bc..ae34418d1da633f445afcee71e39410da6e3999e 100644 (file)
@@ -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 {
index c5c1be31f1e0a9823544902fa758e4df94d20d01..0d4518a632b59c57339d4d151ca2e64d806d43ca 100644 (file)
@@ -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 {