Search code examples
jsonpathwiremock

Wiremock matchesJsonPath checking array values ignoring the order


I am trying to improve the code to prevent errors. I have a couple of requests that can come in these forms, 1:

 {
   "idUser": "1234",,
   "ids": ["3", "1"]
}

or 2:

{
  "idUser": "1234",,
  "ids": ["1", "3"]
}

And I have this Json Match:

{
  "request": {
    "urlPath": "mypath/rest/",
    "bodyPatterns": [
      {
        "matchesJsonPath": {
          "expression": "$..ids[0]",
          "contains": "1"
        }
      },
      {
        "matchesJsonPath": {
          "expression": "$..ids[1]",
          "contains": "3"
        }
      }
    ]
  },
  "response": {
  }
}

How can I make a "contains" in a regex that ignores the order of ids. I have tried :

 "matchesJsonPath": "$[?(@..ids =~ /[1-3]+/]"
    
    {
      "matchesJsonPath": {
         "expression": "$..ids",
         "contains": "1"
       }
    },
    {
       "matchesJsonPath": {
         "expression": "$..ids",
         "contains": "3"
       }
    }

** In case 1 it would not work and in case 2 it would.

Thanks so much!


Solution

  • I think the issue is coming from your expression, but I'm not a jsonPath expert. I don't think you need to use the expression/includes notation. Something like this should work:

    [{
        "matchesJsonPath": "$.ids[?(@ == '1')]"
    },
    {
        "matchesJsonPath": "$.ids[?(@ == '3')]"
    }]
    

    I tested this out and if you have "ids": ["1", "3"] or "ids": ["3", "1"], it will return a match. If you only have "ids": ["1"] or "ids": ["3"], it won't return a match.