Search code examples
restfixturesfitnesse

How can I check a JSON array using RestFixture?


I have a JSON array like this:

[
    {
        "Id": 1,
        "Host": {
            "Id": 1,
            "LoginId": "abc"
        }
    },
    {
        "Id": 2,
        "Host": {
            "Id": 3,
            "LoginId": "def"
        }
    }
]

I want to check the occurence of Host.LoginId == "abc". If my array was in a fixed order, I could check with jsonbody[0].Host.LoginId=="abc".

However, my array is not in any particular order, so I cannot check on the first element. How can I check a particular occurence anywhere in a JSON array?


Solution

  • From GitHub:

    RestFixture allows an expectation cell to be interpreted as JavaScript if it is preceded by /* javascript */. It must then return a value than can be mapped to true or false. However, the use of the return statement throws an error.

    The following code is working as expected:

    /* javascript */ 
    var found = false; 
    for(var x in jsonbody){
        if (jsonbody[x].Host.LoginId=="abc") {
            found = true;
        } 
    }
    found;
    

    This is inserted as a whole in the fixture:

    | GET | URL | 200 | Content-Type : application/json | /* javascript */ (etc) |