JSON Comparison in APEX

JSON Comparison in APEX
Photo by Raquel Martínez / Unsplash

If you are someone who often works with integrations and deal with JSON day in day out, you will know how much of a pain it is to debug those integration failures. Especially the one that involves failures due to mismatch in JSON structure/schema. More often than not we usually end up comparing each key of the JSON we have sent vs. the JSON the external system has shared or vice versa. For a significantly large JSON this is a mammoth task and a nightmare. Agree?

JSON Comparator : that too order-insensitive to the rescue

I have come up with a simple APEX code that can compare two JSON by leveraging the equals() and hashCode() methods provided by Salesforce. Irrespective of the values in the LHS and RHS, the code only considers the keys to identify the schema/structure and then compares to see if they are equal or not. Besides the code can ignore the order of keys - which means if you have the JSONs where the order of the keys are different it will still compare based on the overall schema only.

You can make it to an order-sensitive comparator by simply commenting a line in the code
hashCode() implementation is relevant only if you are looking for using JSON as keys in Map

Checkout the examples below or buy now and try it for yourself.

The code has been tested with large JSON structures like FHIR Resources
The UI in the below snapshots is not part of the library.

Comparison with difference in order of keys

Also check JSON viewer and Editor

I have also built an LWC to visually view and edit JSON files similar to the one you see in the above snapshot. Check it here

About the author
Muralidhar Sampathirao

Muralidhar Sampathirao

Sr Technical Consultant @ Salesforce • With thrdz I am designing the building blocks for Enterprise Applications • Articles, opinions and resources expressed/shared are entirely my personal views.


DZining the building blocks for Enterprise Applications


Great! You’ve successfully signed up.

Welcome back! You've successfully signed in.

You've successfully subscribed to THR(EA)DZ.

Success! Check your email for magic link to sign-in.

Success! Your billing info has been updated.

Your billing was not updated.