Search code examples
javajmeterread-writeweb-api-testing

How can we validate json based on key value pair in Jmeter


I haved worked around with Jmeter for load Testing. But now i am focusing on api automation.

Reading file from CSV for the endpoints and Response expected, only challenge i am facing whether how to validate the json based on key value pair, so that i can validate only those data in which i am interested and not whole JSON body.

In java using eclipse we can do this using below Method:

JSONObject obj1=null,obj2=null;

        obj1=new JSONObject(actual);
        obj2=new JSONObject(required);
    Iterator<?> keys = obj2.keys();
    while( keys.hasNext() ) {
         String key = (String)keys.next();
        if(obj2.get(key) instanceof JSONArray)
        {
            if(!compareJSONArray(obj2.getString(key),obj1.getString(key)))
            {return false;}
            status=true;
        }else if(obj2.get(key) instanceof JSONObject)
        {
            if(!compareJSON(obj2.getString(key),obj1.getString(key)))
            {return false;}
            status=true;    
        }else{
            if(obj2.getString(key).equalsIgnoreCase(obj1.getString(key)))
                    {

                status=true;
                    }
            else{
                return false;
            }

        }

How can i do this following in Jmeter. Please Help


Solution

  • You can use JSON Path Assertion to validate JSON responses using JSON Path language expressions.

    JSON Path Assertion can be installed using JMeter Plugins Manager

    JMeter JSON Path Assertion via Plugins Manager


    Another option is using JSR223 Assertion and Groovy language. Groovy is almost fully Java-compatible so you should be able to re-use your existing Java code. Alternatively be aware that Groovy has built-in JSON support so you can re-implement your JSON comparison logic using Groovy style scripting.