推荐json-validator-go包

json-validator-go使用方法

使用方法很简单,和json.Valid的使用方法类似,示例代码如下:

package main

import (
	"fmt"
	"github.com/luduoxin/json-validator-go/validator"
)

func main() {
	dataStr := `{"foo":"bar"}`
	res := validator.Valid([]byte(dataStr))
	fmt.Println(res)
}

可以仔细阅读如下测试用例并运行一下看看效果:

package main

import (
	"fmt"
	"github.com/luduoxin/json-validator-go/validator"
)

func main() {
	var validTests = []struct {
		data string
		ok   bool
	}{
		{`foo`, false},
		{`}{`, false},
		{`{]`, false},
		{`123`, false},
		{`123.5`, false},
		{`0.5`, false},
		{`true`, false},
		{`false`, false},
		{`null`, false},
		{`[1,2,3]`, false},
		{`["a","b","c"]`, false},
		{`{"foo":bar}`, false},
		{`[{"foo":"bar"},]`, false},
		{`{}`, true},
		{`[]`, true},
		{`[{}]`, true},
		{`{"foo":"bar"}`, true},
		{`{"foo":"bar","bar":{"baz":["qux"]}}`, true},
		{`[{"a":"[\"c\":\"d\"]"}]`, true},
		{`[{"a":[]}]`, true},
		{` {"a":"b"}`, true},
		{` {"a":"b"} `, true},
		{`{"a":"b"} `, true},
		{`{"a": "b"} `, true},
	}

	for _, tt := range validTests {
		if ok := validator.Valid([]byte(tt.data)); ok != tt.ok {
			fmt.Println("not pass")
		}
	}
}

运行后没有输出,说明所有用例都是通过的。