2

When I get an array of objects in JSON response, they might be represent in a different order.

Sometimes I get this

JSON.parse(response.body) # => [{"a" => "b"}, {"c" => "d"}]

or this

JSON.parse(response.body) # => [{"c" => "d"}, {"a" => "b"}]

But for me both results are correct. What is the easiest way to test which objects I have in response regardless of their order?

4
  • 1
    possible duplicate of Comparing ruby hashes Commented Nov 5, 2012 at 15:30
  • Do you want to compare the two or do you just want to check for the existence of certain keys? Commented Nov 5, 2012 at 15:35
  • @padde, I want to compare two or more hashes in the array. But I don't want to compare their order in the array. Commented Nov 5, 2012 at 15:42
  • possible duplicate of How do I compare two hashes? Commented Nov 8, 2012 at 13:40

2 Answers 2

3

You can convert it into a set-like structure using a hash.

first_response.inject({}){|s, h| s[h] = true; s}

will be the same as

second_response.inject({}){|s, h| s[h] = true; s}
Sign up to request clarification or add additional context in comments.

Comments

2

Along with its other useful features, the json spec gem has a be_json_eql matcher which works without respect to order.

1 Comment

I'm not sure be_json_eql is order independent. The code looks like @actual, @expected = scrub(actual_json, @path), scrub(@expected_json) and then does a straight @actual == @expected. the scrub method is in charge of excluding keys you don't want to be part of the comparison (e.g. updated_at), and 'normalizing' the JSON, which just calls either JSON.pretty_generate or to_json.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.