Commit 3f7a35d9 authored by Matt Layher's avatar Matt Layher Committed by Brad Fitzpatrick

encoding/json: add Valid for checking validity of input bytes

Fixes #18086

Change-Id: Idc501dd37893e04a01c6ed9920147d24c0c1fa18
Reviewed-on: https://go-review.googlesource.com/34202Reviewed-by: default avatarBrad Fitzpatrick <bradfitz@golang.org>
Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
parent 1f93ba66
......@@ -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 {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment