Skip to content

bijukunjummen/json-conditional-expression

Repository files navigation

Json Expression Evaluator

This is a small Java based library to create and evaluate a json based conditional expression.

Given a Json which looks like this:

{
    "someKey": "someValue",
    "otherKey": "otherValue"
}

and an expression represented the following way:

{
    "equals": [
        "/someKey", "someValue"
    ]
}

Running a code of the following type:

val jsonExpressionEvaluator: JsonExpressionEvaluator = JsonExpressionEvaluator(ObjectMapper())
jsonExpressionEvaluator.matches(expr, json) //returns true

Details of the Json Expression

The expression follows a very simple pattern, an operator followed by an array of details. It is inspired by the JsonLogic project.

For eg.

{
    "equals": [
        "/someKey", "someValue"
    ]
}

means that the json should be matched on a Json Pointer called "/someKey" and if that value is "someValue" then the expression is true

Here are a few more examples:

{
    "contains": [
        "/someCollection", ["a", "b"]
    ]
}
{
    "containsAnyOf": [
        "/someCollection", ["a", "b"]
    ]
}
{
    "not": [
        {
            "equals": [
                "/someKey",
                "someValue"
            ]
        }
    ]
}
{
    "or": [
        {
            "equal": [
                "/someKey", "someValue"
            ]
        },
        {
            "equal": [
                "/otherKey", "otherValue"
            ]
        }
    ]
}
{
    "and": [
        {
            "equal": [
                "/someKey", "someValue"
            ]
        },
        {
            "equal": [
                "/otherKey", "otherValue"
            ]
        }
    ]
}

The expression can support fairly complex conditions like the following:

{
    "and": [
        {
            "equal": [
                "/someKey", "someValue"
            ]
        },
        {
            "or": [
                {
                    "equal": [
                        "/someKey", "someValue"
                    ]
                },
                {
                    "equal": [
                        "/otherKey", "otherValue"
                    ]
                }
            ]
        }
    ]
}

Usage

Through a Gradle dependency:

implementation 'com.github.bijukunjummen:json-conditional-expression:0.5.0'

Or via maven:

<dependency>
	<groupId>com.github.bijukunjummen</groupId>
	<artifactId>json-conditional-expression</artifactId>
	<version>0.5.0</version>
	<type>pom</type>
</dependency>

About

Json Based Boolean expression evaluator in Java

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages