✅JSON Patch Test Operation

Verify values before applying changes
RFC 6902
test operation

What is the Test Operation?

The test operation checks if the value at the specified path matches the expected value. If the test fails, evaluation stops at that operation. This enables conditional patching and optimistic concurrency control.

Syntax

{ "op": "test", "path": "/path/to/check", "value": <expected value> }

Examples

Test Before Update

Verify a value before replacing it

Patch:
[ { "op": "test", "path": "/version", "value": 1 }, { "op": "replace", "path": "/version", "value": 2 } ]
Before:
{ "version": 1, "data": "..." }
After:
{ "version": 2, "data": "..." }

Test Object Match

Verify an entire object matches

Patch:
{ "op": "test", "path": "/user", "value": { "id": 1 } }
Before:
{ "user": { "id": 1 } }
After:
Patch succeeds if match, fails otherwise

Conditional Delete

Only remove if value matches

Patch:
[ { "op": "test", "path": "/status", "value": "pending" }, { "op": "remove", "path": "/status" } ]
Before:
{ "status": "pending" }
After:
{ }

Real World: Optimistic Concurrency Check

Update only if nobody else touched the record

Patch:
[ { "op": "test", "path": "/version", "value": 3 }, { "op": "replace", "path": "/version", "value": 4 }, { "op": "replace", "path": "/status", "value": "shipped" } ]
Before:
{ "version": 3, "status": "packed" }
After:
{ "version": 4, "status": "shipped" }

Common Use Cases

  • Optimistic concurrency control
  • Conditional updates based on current state
  • Preventing race conditions
  • Validating assumptions before changes

Best Practices

  • Place test operations before related modifications
  • Use for version checking and conflict detection
  • Deep equality comparison for objects and arrays
  • Essential for safe concurrent updates

Test Operation FAQ

What happens when a test operation fails?

Patch evaluation stops at the failed test. RFC 6902 does not require rollback of earlier operations, so place tests before the writes they guard and verify your implementation.

Is the number 1 equal to 1.0 in a test?

RFC 6902 compares numbers mathematically, so 1 and 1.0 match. But 1 and "1" do not: a number never equals a string, and that type mismatch is the most common test failure.

Where should test operations go in a patch?

Before the operations they guard. Operations run in order, so a test only protects changes that come after it.

Try the Test Operation Now

Use our free online JSON Patch generator to create test patches instantly

🚀 Open JSON Patch Generator