该库的主要目的是集成到使用json的测试中,并提供人类可读的测试结果输出。jsondiff可以比较两个json项并返回详细的比较报告。
目前,它可以检测到几种类型的差异:
- FullMatch -表示项目完全相同。
- SupersetMatch——表示第一项是第二项的超集。
- NoMatch -意味着对象是不同的。
type Options
```go type Options struct { Normal Tag Added Tag Removed Tag Changed Tag Skipped Tag SkippedArrayElement func(n int) string SkippedObjectProperty func(n int) string Prefix string Indent string PrintTypes bool ChangedSeparator string // When provided, this function will be used to compare two numbers. By default numbers are compared using their // literal representation byte by byte. CompareNumbers func(a, b json.Number) bool // 不打印匹配的项,默认全打印 SkipMatches bool }
func DefaultConsoleOptions() Options // 在控制台输出 func DefaultHTMLOptions() Options // 输出为HTML func DefaultJSONOptions() Options // 输出为json
<a name="zSsFe"></a>
### type [Tag](https://github.com/nsf/jsondiff/blob/1e845ec5d249/jsondiff.go#L40)
```go
type Tag struct {
Begin string
End string
}
Demo
NoMatch
func main() {
a1 := []byte(`{"a": 1, "b": 2, "c": 3}`)
a2 := []byte(`{"a": 1, "c": 3, "d" : 4}`)
opts := jsondiff.DefaultHTMLOptions()
diffV,diffS := jsondiff.Compare(a1,a2,&opts)
fmt.Println(diffV)
fmt.Println(diffS)
}
SupersetMatch
func main() {
a1 := []byte(`{"a": 1, "b": 2, "c": [1,2,3]}`)
a2 := []byte(`{"a": 1, "b": 2, "c": [1]}`)
opts := jsondiff.DefaultConsoleOptions()
diffV,diffS := jsondiff.Compare(a1,a2,&opts)
fmt.Println(diffV)
fmt.Println(diffS)
}
--------------------------------或--------------------------------
func main() {
a1 := []byte(`{"a": 1, "b": 2, "c": {"c1":1,"c2":2}}`)
a2 := []byte(`{"a": 1, "b": 2, "c": {"c1":1}}`)
opts := jsondiff.DefaultConsoleOptions()
diffV,diffS := jsondiff.Compare(a1,a2,&opts)
fmt.Println(diffV)
fmt.Println(diffS)
}