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)) 
0

1 Answer 1

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? 
Sign up to request clarification or add additional context in comments.

5 Comments

What about an array of JSON response? [{},{}].eqls?[{},{}]?
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...
Yes both are arrays, The order doesn't matter.
How do I correctly parse/read a file that starts with [] instead of {}? JSON.parse can't parse the array.
Yes it can: JSON.parse('[{"a":1, "b":2}, {"a":2, "b":1}]') => [{"a"=>1, "b"=>2}, {"a"=>2, "b"=>1}]

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.