Skip to main content how to compare two deeply nested json objects? : r/golang

Get the Reddit app

Scan this QR code to download the app now
Or check it out in the app stores
r/golang icon
r/golang icon
Go to golang

how to compare two deeply nested json objects?

help

Hey everyone, I am calling an api which returns a json. And i have. json file on local. I want to check if they are same or not. Do I have to loop through both jsons and compare the values or is there any better way of solving this problem.

The more the merrier with AT&T's Bundle of 3. Save on your Apple favorites this holiday season.
Clickable image which will reveal the video player: The more the merrier with AT&T's Bundle of 3. Save on your Apple favorites this holiday season.
Sort by:
Best
Open comment sort options

If all you need is to check whether they equal or not, just do bytes.Equal.

If you are looking for an accurate diff you can use testfy's JSON Equal here.

Profile Badge for the Achievement Top 1% Commenter Top 1% Commenter

That function introduces an extraneous *testing.T (for this context), which is hard to fake up in a non-testing context because it wants to fail if the two things are not equal, which is basically a panic.

You can take the source of it and build a version without the t value. Basically use reflect.DeepEqual on the result of unmarshaling into the two anys.

More replies
More replies

reflect.DeepEqual on map[string]any instances you unmarshaled your json data into.

If you only care whether they're identical you can just compare the bytes.

Only if you can guarantee the ordering of keys is the same in each though, right?

More replies

Only if you can guarantee the ordering of keys is the same in each though, right?

More replies

You can do this: reflect.DeepEqual(newConfig, globals.Config)

https://pkg.go.dev/github.com/google/go-cmp/cmp#Equal

Camp.equal is the best output I’ve seen for test cases and just debugging in general.

More replies