1

I have a file text.json and I have an JSON HTTP response. What's a good to check if they are equal?

Here's what I have but I think there's a better solutions.

JSON.parse(response["data"]).eql?(File.read(text.json))
Sten Kin
  • 2,485
  • 3
  • 23
  • 29

1 Answers1

3

You need to parse both ends of your test:

JSON.parse(response["data"]).eql?(JSON.parse(File.read(text.json)))

Edit
If you want to test an array of JSONs, and you are not sure that the order will be the same in the file meaning [{a:1, b:2}, {a:2, b:1}] should equal [{a:2, b:1}, {a:1, b:2}], you'll need to sort them first (see here for more techniques):

 JSON.parse(response["data"]).sort.eql?(JSON.parse(File.read(text.json)).sort)

Edit 2
Since Hashes don't sort well, the above won't work. You could use one of the other techniques:

from_response = JSON.parse(response["data"])
from_file = JSON.parse(File.read(text.json))

(from_response & from_file) == from_response
(from_response - from_file).empty?
Community
  • 1
  • 1
Uri Agassi
  • 36,848
  • 14
  • 76
  • 93
  • What about an array of JSON response? `[{},{}].eqls?[{},{}]`? – Sten Kin Mar 31 '14 at 15:46
  • I'm not sure I understand your question - the response is an array of JSON, and the file has an array of JSON? If the order of the JSONs is important, then yes, otherwise, you'd need to tweak the solution... – Uri Agassi Mar 31 '14 at 15:48
  • Yes both are arrays, The order doesn't matter. – Sten Kin Mar 31 '14 at 15:48
  • How do I correctly parse/read a file that starts with `[]` instead of `{}`? `JSON.parse` can't parse the array. – Sten Kin Mar 31 '14 at 15:58
  • Yes it can: `JSON.parse('[{"a":1, "b":2}, {"a":2, "b":1}]')` => `[{"a"=>1, "b"=>2}, {"a"=>2, "b"=>1}]` – Uri Agassi Mar 31 '14 at 16:04