testify: JSONEq returning error due to difference in ordering

The following snippet returns error:

require.JSONEq(t, `[
		{"uid":"0x2","name@en":"pho\ton"},
		{"uid":"0x1","name":"pho\ton"}
		]`, `[
			{"uid":"0x1","name":"pho\ton"},
			{"uid":"0x2","name@en":"pho\ton"}
			]`
	)

Is there any work-around for this? This seems like a bug to me.

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 7
  • Comments: 15

Most upvoted comments

Json is unordered collection (see json.org)

In JSON, they take on these forms: An object is an unordered set … An array is an ordered collection …

from https://www.json.org/json-en.html

Json is unordered collection (see json.org)

@brackendawson hi!

If JSON array is unordered collection by design, then why does JSONEq take into account the order of the elements? 🤔 This results in either flacky tests or additional testing code.

If JSON array is unordered collection by design

But JSON array is an ordered collection.

If a given user’s isn’t ordered by their design, then they should expect to need some acrobatics when reasoning with their JSON data. I think that JSONEq should expect to work with JSON.

I don’t want anything to fail

You and me both, buddy.

at least provide an option to ignore orders…

What would you call it? assert.JSONElementsMatch I’d say no because ElementsMatch can only be called on slices and arrays. assert.JSONEqExeptWithArraysInAnyOrder I’d say no because it’s deliberately silly.

I did provide a sane example. I don’t think this issue warrants any change. If you can describe a good change that would address this need then comment and I’ll re-open.

at least provide an option to ignore orders…

@roppa @black-desk maybe I’m misunderstanding your messages, but exactly because objects are unordered, OPs test should pass.

The OP’s JSON blobs are both arrays, which are ordered, and the elements are in different orders, this is correctly failing.

I don’t know why we’re mentioning that JSON objects are unordered, it’s not relevant to the OP’s question. Perhaps we’ve all answered “that question” too many times and we missed that this is not an instance of “that question”.

Anyone that would like to assert that two JSON arrays contain the same elements will need to first unmarshal them, like this:

func TestJSON(t *testing.T) {
	var expected, actual []interface{}
	require.NoError(t, json.Unmarshal([]byte(`[
		{"uid":"0x2","name@en":"pho\ton"},
		{"uid":"0x1","name":"pho\ton"}
		]`), &expected))
	require.NoError(t, json.Unmarshal([]byte(`[
		{"uid":"0x1","name":"pho\ton"},
		{"uid":"0x2","name@en":"pho\ton"}
		]`), &actual))
	require.ElementsMatch(t, expected, actual)
}

This is not a bug.