djangofan
djangofan

Reputation: 29669

Filtering down a Karate test response object to get a sub-list?

Given this feature file:

Feature: test

  Scenario: filter response
    * def response =
    """
    [ 
        {
            "a": "a",
            "b": "a",
            "c": "a",
        },
        {
            "d": "ab",
            "e": "ab",
            "f": "ab",
        },
        {
            "g": "ac",
            "h": "ac",
            "i": "ac",
        }
    ]
    """
    * match response[1] contains { e: 'ab' }

How can I filter the response down so that it is equal to:

{
    "d": "ab",
    "e": "ab",
    "f": "ab",
}

Is there a built-in way to do this? In the same way as you can filter a List using a Java stream?

Upvotes: 2

Views: 3934

Answers (1)

Neodawn
Neodawn

Reputation: 1096

Sample code:

Feature: test

  Scenario: filter response
    * def response =
    """
    [ 
        {
            "a": "a",
            "b": "a",
            "c": "a",
        },
        {
            "d": "ab",
            "e": "ab",
            "f": "ab",
        },
        {
            "g": "ac",
            "h": "ac",
            "i": "ac",
        }
    ]
    """
    * def filt = function(x){ return x.e == 'ab' }
    * def items = get response[*]
    * def res = karate.filter(items, filt)    
    * print res

Upvotes: 3

Related Questions