Super late to the party here.

There is a popular testing package in golang called require github.com/stretchr/testify/require and it will do this for you.

func TestJsonEquality(t *testing.t) { 
  expected := `{"a": 1, "b": 2} `
  actual := ` {"b":   2, "a":   1}`
  require.JSONEq(t, expected, actual)
}

GoDocs: https://godoc.org/github.com/stretchr/testify/require#JSONEqf

Answer from Highstead on Stack Overflow
🌐
Go Packages
pkg.go.dev › github.com › wI2L › jsondiff
jsondiff package - github.com/wI2L/jsondiff - Go Packages
The option accepts a variadic list of JSON Pointers, which all individually represent a value in the source document. However, if the value does not exist in the source document, the value will be considered to be in the target document, which allows to ignore add operations. For example, let's generate the diff between those two JSON documents:
🌐
GitHub
github.com › yudai › gojsondiff
GitHub - yudai/gojsondiff: Go JSON Diff · GitHub
When you prefer the delta format of jsondiffpatch, add the -f delta option. ... { "arr": { "2": { "str": [ "pek3f", "changed" ] }, "3": { "1": [ "1", "changed" ], "_t": "a" }, "_t": "a" }, "obj": { "arr": { "2": { "str": [ "eafeb", "changed" ] }, "_t": "a" }, "new": [ "added" ], "num": [ 19, 0, 0 ], "obj": { "num": [ 14, 9999 ], "str": [ "efj3", "changed" ] } } } Give a diff file in the delta format and the JSON file to the jp command.
Author   yudai
Top answer
1 of 4
48

Super late to the party here.

There is a popular testing package in golang called require github.com/stretchr/testify/require and it will do this for you.

func TestJsonEquality(t *testing.t) { 
  expected := `{"a": 1, "b": 2} `
  actual := ` {"b":   2, "a":   1}`
  require.JSONEq(t, expected, actual)
}

GoDocs: https://godoc.org/github.com/stretchr/testify/require#JSONEqf

2 of 4
19

You need to pass pointers to Decode and Unmarshal. I put up a runnable sample with func JSONEqual(a, b io.Reader) and JSONBytesEqual(a, b []byte), both returning (bool, error). You can compare a request body to your static expected content (like you're trying to do in the question) by wrapping your expected content using bytes.NewBuffer or strings.NewReader. Here's the code:

package main

import (
    "encoding/json"
    "fmt"
    "io"
    "reflect"
)

// JSONEqual compares the JSON from two Readers.
func JSONEqual(a, b io.Reader) (bool, error) {
    var j, j2 interface{}
    d := json.NewDecoder(a)
    if err := d.Decode(&j); err != nil {
        return false, err
    }
    d = json.NewDecoder(b)
    if err := d.Decode(&j2); err != nil {
        return false, err
    }
    return reflect.DeepEqual(j2, j), nil
}

// JSONBytesEqual compares the JSON in two byte slices.
func JSONBytesEqual(a, b []byte) (bool, error) {
    var j, j2 interface{}
    if err := json.Unmarshal(a, &j); err != nil {
        return false, err
    }
    if err := json.Unmarshal(b, &j2); err != nil {
        return false, err
    }
    return reflect.DeepEqual(j2, j), nil
}

func main() {
    a := []byte(`{"x": ["y",42]}`)
    b := []byte(`{"x":                  ["y",  42]}`)
    c := []byte(`{"z": ["y", "42"]}`)
    empty := []byte{}
    bad := []byte(`{this? this is a test.}`)

    eq, err := JSONBytesEqual(a, b)
    fmt.Println("a=b\t", eq, "with error", err)
    eq, err = JSONBytesEqual(a, c)
    fmt.Println("a=c\t", eq, "with error", err)
    eq, err = JSONBytesEqual(a, empty)
    fmt.Println("a=empty\t", eq, "with error", err)
    eq, err = JSONBytesEqual(a, bad)
    fmt.Println("a=bad\t", eq, "with error", err)
}

It outputs:

a=b  true with error <nil>
a=c  false with error <nil>
a=empty  false with error EOF
a=bad    false with error invalid character 't' looking for beginning of object key string
🌐
Go Packages
pkg.go.dev › github.com › nsf › jsondiff
jsondiff package - github.com/nsf/jsondiff - Go Packages
The lib can compare two json items and return a detailed report of the comparison. At the moment it can detect a couple of types of differences:
🌐
GitHub
github.com › josephburnett › jd
GitHub - josephburnett/jd: JSON diff and patch · GitHub
jd is a commandline utility and Go library for diffing and patching JSON and YAML values. It supports a native jd format (similar to unified format) as well as JSON Merge Patch (RFC 7386) and a subset of JSON Patch (RFC 6902).
Author   josephburnett
🌐
Reddit
reddit.com › r/golang › fancy diff output for json objects
r/golang on Reddit: Fancy diff output for JSON objects
September 6, 2016 -

Well, it came to me when I was writing 101st test for API. There are many asserters in golang world, but I needed readable output. Especially when it came to output a diff for 2 huge objects - expected and actual API responses. I got inspired by http://tlrobinson.net/projects/javascript-fun/jsondiff/ and implemented this one for Go: https://github.com/elgris/jsondiff

Hope you will find it useful for your tests. Or point me to another useful tool that visualizes diffs in golang world :)

🌐
Reddit
reddit.com › r/golang › jsondiff: json diff library for go based on rfc6902 (json patch)
r/golang on Reddit: jsondiff: JSON diff library for Go based on RFC6902 (JSON Patch)
December 7, 2020 - The conceptual difference compared to JSON Patch is that JSON Merge Patch is similar to a diff file. It simply contains the nodes of the document which should be different after execution.
🌐
Reddit
reddit.com › r/golang › built a tool for deep json comparison - seeking input on array diff visualization
r/golang on Reddit: Built a Tool for Deep JSON Comparison - Seeking Input on Array Diff Visualization
July 30, 2024 -

Hey r/golang community,

I've been grappling with a recurring challenge in my work: comparing large, deeply nested JSON files. To tackle this, I created a CLI tool in Go that helps highlight differences between two JSON files with high precision.

The tool is relatively compact, about 200 lines of code, and handles different types of changes well, including additions, deletions, and type mismatches. However, I'm looking to improve how differences within arrays are displayed. Currently, if an item at the beginning of an array is modified or removed, all subsequent items are marked as changed, which isn't very helpful for quick analysis.

Here's where I could use your collective wisdom:

  1. Visualization Techniques: Does anyone have suggestions for more intuitive ways to display array differences? Maybe a method that effectively pinpoints and isolates changes without cascading the entire array?

  2. Code Feedback: I'd love to get some feedback on the implementation. I'm sure there are optimizations and best practices that I could apply to enhance the tool's performance and usability.

I'm looking forward to your insights and suggestions. Let's make JSON comparisons easier for everyone!

You can check out the tool and contribute here: https://github.com/phplego/jcmp

Thank you all in advance!

Find elsewhere
🌐
Go Forum
forum.golangbridge.org › getting help
Best way to make comparisions between two json - Getting Help - Go Forum
August 4, 2022 - I have some issues when comparing two json structures. I have to compare what is inside a json file against what is in the server so I can update the server´s info propertly. For example: If I have this info in the json file { "envs": [ { "env": "test", "books": [ { "name": "book1", "read": true }, { "name": "book2", "read": true }, { "name": "book3", "read": true } ] } ] } and getting this info from the server { "name": "Default", "...
🌐
Go Packages
pkg.go.dev › github.com › elgris › jsondiff
jsondiff package - github.com/elgris/jsondiff - Go Packages
A simple little tool that produces readable diff of 2 JSON-able (read "convertible to map[string]interface{}") objects. Useful for diagnostics or debugging · go get github.com/elgris/jsondiff · Coloured output tested with bash only, not sure how it will behave with other terminals.
🌐
Spiral
spiral.dev › blog › go-unit-tests-with-json-compare
Spiral Framework: Go Unit Tests with JSON Compare
package simple import ( "encoding/json" "testing" "github.com/nsf/jsondiff" ) func TestSortJsonCompareStage2(t *testing.T) { in := []Figure{ {"circle", "white"}, {"square", "black"}, {"circle", "black"}, {"square", "white"}, {"square", "red"}, } expectedJsonStr := ` [ { "Type": "circle", "Color": "black" }, { "Type": "circle", "Color": "white" }, { "Type": "square", "Color": "black" }, { "Type": "square", "Color": "red" }, { "Type": "square", "Color": "white" } ] ` out := Sort(in) outJsonStr, err := json.MarshalIndent(out, "", " ") if err != nil { t.Fatal("error marshaling package", err) } //fmt.Println(string(outJsonStr)) diffOpts := jsondiff.DefaultConsoleOptions() res, diff := jsondiff.Compare([]byte(expectedJsonStr), []byte(outJsonStr), &diffOpts;) if res != jsondiff.FullMatch { t.Errorf("the expected result is not equal to what we have: %s", diff) } }
🌐
Spiralscout
spiralscout.com › home › go unit tests with json compare
Go Unit Tests with JSON Compare | Spiral Scout Company News
June 22, 2023 - NoMatch – means objects are different. Being a superset means that every object and array which don’t match completely in a second item must be a subset of a first item. For example: ... Now, the unit tests can be written in two stages. Instead of defining the expected output, we simply print the output of the sorting function for the given inputs: Then we run the test to get the output in formatted JSON directly in the console:
🌐
Go Packages
pkg.go.dev › github.com › aereal › jsondiff
jsondiff package - github.com/aereal/jsondiff - Go Packages
go install github.com/aereal/jsondiff/cmd/jsondiff@latest jsondiff -only '.d' ./testdata/from.json ./testdata/to.json # --- from.json # +++ to.json # @@ -1,2 +1,2 @@ # -4 # +3 ... See LICENSE file. Expand ▾ Collapse ▴ ... This section is empty. ... var ErrEitherOnlyOneOption = errors.New("either of only one of Ignore() or Only() must be specified") func Diff(from, to *Input, opts ...Option) (string, error)
🌐
Google Groups
groups.google.com › g › golang-nuts › c › VYLDHl0t9R0
JSON Compare
json1 := json.RawMessage(`{"foo":{"a":1}}`) json2 := json.RawMessage(`{"foo":{"b":8}}`) err := td.EqDeeplyError(json1, td.JSON(json2))
🌐
LinkedIn
linkedin.com › posts › nakul-bhandare-a2455b14b_github-nakulbhandarejsondiff-json-diff-activity-7051054042688458752-qybc
Nakul Bhandare on LinkedIn: GitHub - nakulbhandare/jsondiff: JSON diff library for Go.
April 10, 2023 - Whether you're a developer working on a large-scale project or simply need to compare JSON data for testing purposes, my JSON diff library is a powerful tool that can help you save time and reduce errors. So, if you're looking for an easy way to compare JSON objects, be sure to check out my new JSON diff library. You can find the library on GitHub, and I encourage you to give it a try and share your feedback. #softwaredevelopment #golang #json #performance
🌐
Snyk
snyk.io › advisor › golang packages › jsondiff
jsondiff - golang Package Health Analysis | Snyk
Learn more about jsondiff: package health score, popularity, security, maintenance, versions and more.
🌐
GitHub
github.com › apokalyptik › go-jsondiff › blob › master › go-jsondiff.go
go-jsondiff/go-jsondiff.go at master · apokalyptik/go-jsondiff
Operation string `json:"o,omitempty"` // M, - Changes map[string]Diff `json:"v,omitempty"` Resultrevision int `json:"ev,omitempty"` CurrentVersion string `json:"cv,omitempty"` ChangesetIds []string `json:"ccids,omitempty"` ChangesetId string `json:"ccid,omitempty"` Error int `json:"error,omitempty"` } ·
Author   apokalyptik
🌐
Libhunt
go.libhunt.com › jsondiff-alternatives
jsondiff Alternatives - Go JSON | LibHunt
Add another 'JSON' Package ... jsondiff jsondiff is a Go package for computing the diff between two JSON documents as a series of RFC6902 (JSON Patch) operations, which is particularly suitable to create the patch response of a Kubernetes Mutating Webhook for example.