Skip to main content
All CollectionsTutorials
Generic JSONPath Expression to Check if a Number Starts with a Specific Digit
Generic JSONPath Expression to Check if a Number Starts with a Specific Digit
R
Written by Rafael Blanco
Updated over 11 months ago

JSONPath is a powerful tool for querying and filtering JSON data. It allows you to easily extract specific data from a JSON object or array, making it a valuable tool for developers and data analysts alike.

In this article, we will explore how to use JSONPath to validate whether a given number starts with 0, 1, 2, or 3. This can be useful in situations where you need to filter out certain data or perform conditional operations based on the starting digits of a number.

Validating Numbers with JSONPath

To validate if a number begins with 0, 1, 2, or 3 using JSONPath, you can employ the following expression:

$[?(@.body.orderId =~ /^0.*/i || @.body.orderId =~ /^1.*/i || @.body.orderId =~ /^2.*/i || @.body.orderId =~ /^3.*/i)]

Let's break down this expression to understand how it works:

  • The square brackets [] are used for filtering.

  • The ? indicates a filter expression.

  • @.body.orderId represents the path to the "orderId" field in the JSON structure.

  • =~ is the regex match operator in JSONPath.

  • /^0.*/i checks if the "orderId" starts with 0,1,2 or 3 (case-insensitive).

  • || is the logical OR operator, combining multiple conditions.

    If the number meets this condition, it will be returned by the JSONPath query. Otherwise, it will be excluded from the results.

Example

Let's say we have the following JSON data:

{ "body": { "orderId": "12345" } }

Applying the JSONPath expression to this object would return a match, as the "orderId" (12345) starts with 1.

Conclusion

JSONPath provides a concise and powerful way to query and validate JSON data. In this article, we focused on using JSONPath to validate whether a number starts with 0, 1, 2, or 3. The provided expression can be customized for different scenarios, offering flexibility in JSON data validation.

Did this answer your question?