0

I am trying to validate two API JSON response key-value pairs for same key values and throw an error if there is a mismatch in the JSON response.

Eg: 1. www.oldurl.com gives=>

   { "firstName":"alex", "age":31, "dob":"10-12-1988" }

2. www.newurl.com gives =>

   { "firstName":"**alx**", "**ag**":31, "dob":"10-12-1988" }

Here the oldurl and newurl gives the same JSON response but in newurl we see an error in key and values.

Now, I need to catch this error and show the user that there is a mismatch in newurl.com with key firstname and age.

Python code:

import unittest
import requests, json,settings
from requests.auth import HTTPBasicAuth
from jsonschema import validate
class TestOne(unittest.TestCase):
    def setUp(self):

    def test_oldurl(self):
    resp=requests.get('www.oldurl.com',auth=HTTPBasicAuth(settings.USER_NAME,settings.PASSWORD))
    data = resp.text
    print (data)  #Prints json 

    def test_newurl(self):
    resp=requests.get('www.newurl.com',auth=HTTPBasicAuth(settings.USER_NAME,settings.PASSWORD))
    data = resp.text
    print (data)  #Prints json 

now I got two JSON response, How can I validate these two responses. Is there any python libraries that can validate and show any error in keys and values.

note: Both JSON response should be same I am doing this as part of validation to avoid any error in the future response.

I also used schema for one JSON responses key validation alone. used:

    def setUp(self):
    with open('Blueprint_schema.json', 'r') as f:
        self.schema = f.read()
        self.file = f
     validate(json.loads(data), json.loads(self.schema))
     self.assertNotEqual(data,'[]')

but this is helping only for one JSON response key alone. So, I need to compare two API's JSON response while executing or by storing it in two files and opening it and validating. I thought these files validation but it will be more coding so thought of reducing the length of code by validating on runtime itself.

Please suggest your ideas.

1 Answer 1

1
# newurl_resp should also give back same key:value pairs as oldurl was giving

#load JSON Data into Dictionary 
import json
f = open("response_oldurl.json")
oldurl_resp= json.load(f)
f.close()
#type(oldurl_resp) --> <class dict>

oldurl_resp = { "firstName":"alex", "age":31, "dob":"10-12-1988" }
newurl_resp = { "firstName":"**alx**", "**ag**":31, "dob":"10-12-1988"}

approach 1 report errors on the fly

def validate_resp(old_resp,new_resp):
    for old_k,old_v in oldurl_resp.items():

        try:
            if old_k in new_resp:
                new_val = new_resp[old_k]
            else:
                raise KeyError('newurl_response doesn\'t have key: '+old_k)

            try:
                if old_v != new_val:
                    raise ValueError('new value = '+str(new_val)+' doesn\'t match with orignal value = '+str(old_v)+' of key: '+str(old_k))

                    #raise ValueError('new value = {} doesn\'t match with orignal value = {} of key: {}'.format(new_val,old_v,old_k))

            except ValueError as v_err:
                print(v_err.args)

        except KeyError as k_err:
            print(k_err.args)


validate_resp(oldurl_resp,newurl_resp)

#("new value = **alx** doesn't match with orignal value = alex of key: firstName",)
#("newurl_response doesn't have key: age",)

approach 2 saves them for later use

items_with_value_err = []
missing_keys = []

def validate_resp(old_resp,new_resp):
    for old_k,old_v in oldurl_resp.items():
        if old_k in new_resp:
            if new_resp[old_k] != old_v:
                # key is same but new_resp contains different value
                items_with_value_err.append((old_k,old_v,new_resp[old_k]))
        else:
            missing_keys.append(old_k)

    if len(items_with_value_err) == 0 and len(missing_keys) == 0:
        return True
    else:
        return False

print(validate_resp(oldurl_resp, newurl_resp)) #prints False
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you @tanmay for the solution, It will be helpful if you explain the code as it contains two parts
@dow thanks for accepting the answer, glad I could help.
@dow pastebin.com can you paste more complex json here there maybe more edge cases. and you can do print where I am appending the key, values to list approach 2 this will work for everything I guess if all you want to do is print key, values having error
@dow replace that line with this raise ValueError('new value = '+str(new_val)+' doesn\'t match with orignal value = '+str(old_v)+' of key: '+str(old_k))

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.