compare-json (Go)
compare-json-go is the Go port of compare-json — structured JSON comparison with the same semantics as the engine that powers this website. It detects additions, deletions, type changes, and value changes between two JSON values, with control over how keys, values, and arrays are matched. Ships as both a library and a CLI, with zero external dependencies.
Language: Go — distributed via pkg.go.dev. Source code on GitHub.
Installation
go get github.com/unitstack/compare-json-go
Quick Start
Library
package main
import (
"encoding/json"
"fmt"
comparejson "github.com/unitstack/compare-json-go"
)
func main() {
var base, contrast interface{}
json.Unmarshal([]byte(`{"name":"Alice","age":30}`), &base)
json.Unmarshal([]byte(`{"name":"Bob","age":"30","email":"[email protected]"}`), &contrast)
diffs := comparejson.CompareJSON(base, contrast, &comparejson.CompareOptions{
ArrayCompareMethod: comparejson.ArrayCompareByIndex, // or ArrayCompareLCS, ArrayCompareUnordered
})
for _, d := range diffs {
fmt.Println(d.PathString, d.PathBelongsTo, d.DiffType)
}
// name both valueChanged
// age both typeChanged
// email contrast added
}
CLI
# Compare JSON files
compare-json base.json contrast.json
# Array strategies and case-insensitive matching
compare-json -a lcs -k -v base.json contrast.json
# Machine-readable JSON output
compare-json --json-export base.json contrast.json
# Write the report to a file
compare-json -o diff.txt base.json contrast.json
Note: with the stdlib flag package, flags must come before the positional arguments.
Options
| Flag | Description |
|---|---|
-a, --array-compare-method | Array comparison strategy: byIndex (default), lcs, unordered |
-k, --key-case-insensitive | Compare object keys case-insensitively |
-v, --value-case-insensitive | Compare string values case-insensitively |
--numeric-string-equals-number | Treat numeric strings as equal to numbers |
-j, --json-export | Output the differences as JSON |
-o, --output <file> | Write output to a file instead of stdout |
See Comparison Options and Array Comparison Methods for what each setting does.
License
MIT