Forum Discussion

dipsthorat's avatar
dipsthorat
Occasional Contributor
4 years ago
Solved

How to Compare an array from one Json Response to an array from another Json response.

Hi All, I have 2 different json array and need to validate every n each attribute against each other .Earlier I used Message content assertion but I need to do for all array item manually. for examp...
  • nmrao's avatar
    nmrao
    4 years ago

    Here is a sample to compare two lists (books in this case). But you need to adopt the changes as per your data.

     

     

    def expectedJson = '''{
        "book": [
            {
                "title": "Beginning JSON",
                "price": 49.99
            },
    
            {
                "title": "JSON at Work",
                "price": 29.99
            }
        ]
    }'''
    
    def actualJson = '''{
        "book": [
            {
                "title": "JSON at Work",
                "price": 29.99
            },
            {
                "title": "Beginning JSON",
                "price": 49.99
            }
        ]
    }'''
    
    //Note that the order of books are different in the above 
    
    def getJson = { str -> new groovy.json.JsonSlurper().parseText(str)}
    def expectedBooks = getJson(expectedJson).book
    def actualBooks = getJson(actualJson).book
    
    //Check if both lists are sorted and compared
    assert actualBooks.sort() == expectedBooks.sort()