How to validate uniqueness of a field value in the JSON response.
Hello everyone,
Can someone help me how to validate a field, if the value returned in response in unique and contains no duplication.
E,g:
In below JSON, id field occurs multiple times, I want to validate "id" is unique and it's not duplicated in the JSON response.
{
"merchantCategories": [{
"id": "0001",
"description": "Personal & Household Expenses",
}, {
"id": "0002",
"description": "Professional and Financial Services",
}, {
"id": "0003",
Thanks for your time and support.
Regards,
Neil
Comments
-
One option is to use a JSON Assertor then create a custom assertion which involves custom scripting. However, my recommendation is to use XPath. To use XPath for JSON, you need to use an XML Converter to first convert the JSON to XML. Next, chain an XML Transformer to the XML Converter tool. In the XML Transformer, create an extraction with an XPath like
count(distinct-values(/root/merchantCategories/item/id/text())) = count(/root/merchantCategories/item/id)
. In this case, such an XPath would compare the number of distinct (unique) values against the total number of values, returning true/false. Lastly, chain a Diff tool to your XML Transformer to validate the XPath returns "true".1 -
The XPath comparison can also be done with a JSON test and JSON assertor where the regular expression can be used in Value assertion and edit the XPath to comparison count(distinct-values(/root/merchantCategories/item/id/text())) = count(/root/merchantCategories/item/id)
0