pythonjsonpython-3.xvalidationtestautomationfx

How can I validate with a test a json with all the parameters? Python


Example: { "name": "Jocelyne", "age": 30 } and it returns the same. In case someone adds more parameters it fails.


Solution

  • As I understand you correctly, you can write a function like this (to check the keywords)

    import json
    
    def check_json_data(json_str):
        # base key list
        base_keys = json.loads('{ "name": "Jocelyne", "age": 30 }').keys()
        # convert json string to dict
        input_json_data = json.loads(json_str)
        # extract keys
        input_keys = input_json_data.keys()
        # check if there are additional keys in incoming keys
        if set(input_keys) - set(base_keys): # for exact check of key list: set(input_keys) != set(base_keys)
            return None
        else:
            return json_str
    

    Test

    print(check_json_data('{ "name": "Jocelyne", "age": 30, "age2": 30 }'))
    
    print(check_json_data('{ "name": "Jocelyne", "age2": 30 }'))
    
    print(check_json_data('{ "name": "Jose", "age": 33 }'))
    

    None

    None

    { "name": "Joce", "age": "33" }