Instead of converting the JSON response into Object, I use json.loads() to convert it into a Dictionary, and compare them.
def test_login(self, client):
res = return client.post('/login',
data=json.dumps(dict(staff_name='no_such_user', staff_password='password')),
content_type='application/json',
follow_redirects=True)
assert res.status_code == 422
invalid_password_json = dict(message="Staff name and password pair not match",
errors=dict(
resource="Login",
code="invalid",
field="staff_authentication",
stack_trace=None,),
)
assert json.loads(res.data) == invalid_password_json
This way, I do not have to worry about whitespace differences in the JSON response, as well as ordering of the JSON structure. Simply let Python's Dictionary comparison function check for equality.
Answer from Hanxue on Stack OverflowInstead of converting the JSON response into Object, I use json.loads() to convert it into a Dictionary, and compare them.
def test_login(self, client):
res = return client.post('/login',
data=json.dumps(dict(staff_name='no_such_user', staff_password='password')),
content_type='application/json',
follow_redirects=True)
assert res.status_code == 422
invalid_password_json = dict(message="Staff name and password pair not match",
errors=dict(
resource="Login",
code="invalid",
field="staff_authentication",
stack_trace=None,),
)
assert json.loads(res.data) == invalid_password_json
This way, I do not have to worry about whitespace differences in the JSON response, as well as ordering of the JSON structure. Simply let Python's Dictionary comparison function check for equality.
If you do indeed require literal, value-to-value equality between two doctionaries, it would be simpler to compare their json serialization results, otherwise you would need some recursive comparison of dicts and their values
Note: since dicts in python are unsorted collections, you would require passing sort_keys=True to json.dumps, see this question for more details
I need to compare two JSON files that contain a list of dictionaries whose basic format is:
[{"protocol": "S", "type": "", "network": "0.0.0.0", "mask": "0", "distance": "254", "metric": "0", "nexthop_ip": "192.168.122.1", "nexthop_if": "", "uptime": ""}, {"protocol": "O", "type": "", "network": "10.129.30.0", "mask": "24", "distance": "110", "metric": "2", "nexthop_ip": "172.20.10.1", "nexthop_if": "GigabitEthernet0/1", "uptime": "08:58:25"}]Though there are many, many more dictionary items in the list than that shown above. I am not quite sure how best to go about comparing the files to spot differences and return or save those difference to another file, preferably in JSON format, though a CSV would be fine too.
The one gotcha that there may be is I need to exclude, at a minimum, the uptime value as it is constantly changing so it will of course trigger anything looking for changes. Can anyone help get me started please?
» pip install jsoncomparison
» pip install json-diff
» pip install pytest-json