mirror of
https://github.com/golang/go
synced 2024-11-19 22:04:44 -07:00
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>
This commit is contained in:
parent
1f93ba66d6
commit
3f7a35d91c
@ -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 {
|
||||
|
@ -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 {
|
||||
|
Loading…
Reference in New Issue
Block a user