Breadcrumbs

JsonMatch

Testing JSON strings or object instances for matching against a DSL (Domain Specific Language) similar to WHERE clauses in SQL. It is limited to operations on JSON native data types, i.e. string, integer, number, and boolean, but not datetime.

Json Match Overview.png

Under the hood

JsonMatch transforms expressions into semantically equivalent JsonPath expressions, and uses JsonPath internal structures to precompile these expressions. These precompiled JsonPath expressions are then evaluated against arbitrary JSON strings.

Usage

You have to use the matcher(expression: String) operation to retrieve an instance of Matcher. Use this instance to test as many JSON strings (matchesJson(string)) or Objects (matchesAny(object)) for matching your condition. The operation matchesAny() will implicitly call classToJSON() on the given object.

Important note: Call release() when done!

Call 'release()' on the Matcher instance when done to free up internally allocated memory holding the pre-compiled match expression.

Take this JSON snippet:

JSON Object

JSON
{
	"autoRetry": false,
	"autoRetryTime": "PT60S",
	"currentTask": {
		"begin": "2023-07-21T17:33:14.005054Z",
		"name": "wait_for_Godot",
		"stateName": "Waiting for wait_for_Godot"
	},
	"holdTime": "PT60S",
	"id": "000001277983434200003a8ce77fe700a8beba4d",
	"myBoolean": true,
	"myFloat": 3.0,
	"myInteger": 3,
	"myString": "three",
	"originalValues": {
		"aBoolean": true,
		"aFloat": 3.0,
		"aInt": 3,
		"aString": "three"
	},
	"stateId": 0
}

The following expressions are syntactically correct and matchesJson() will return true:

Valid Expressions

SQL
"myBoolean = true AND (myFloat >= 3.0 OR myString IN ['three', 'four', 'five'])"  -- AND, OR, and IN

"autoRetryTime MATCH 'PT[0-9]{2}S' AND autoRetry = true"                          -- MATCH allows for testing against regular expressions

"currentTask.stateName NIN ['Error', 'Abort'] AND originalValues.aInt > 0"        -- NIN (not IN) as opposed to IN, accessing nested attributes by dot notation

Not that you cannot build expressions that compare values of attributes, e.g.

Invalid Expressions

SQL
"myBoolean != originalValues.aBoolean"                                            -- comparing attribute values is not possible

The railroad diagrams of the DSL:

Expression Syntax Diagram (show | hide)
expression_syntax_diagram-20251029-175351.png
📗

Related Pages:

📘

Related Documentation: