Welcome to the new Parasoft forums! We hope you will enjoy the site and try out some of the new features, like sharing an idea you may have for one of our products or following a category.

How to validate uniqueness of a field value in the JSON response.

Neil
Neil Posts: 38
edited June 2017 in SOAtest

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

  • benken_parasoft
    benken_parasoft Posts: 1,306 ✭✭✭

    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".

  • BastiaantB
    BastiaantB Posts: 8
    edited January 2023

    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)