npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

json-expression-eval

v10.0.0

Published

json serializable rule engine / boolean expression evaluator

Readme


Why json-expression-eval?

Need to store complex business rules in a database? Want to evaluate dynamic conditions without eval()? This library lets you:

  • Serialize expressions as JSON - Store rules in databases, send them over APIs
  • 100% type-safe - Full TypeScript support with compile-time validation
  • Extensible - Add custom functions for domain-specific logic
  • Debug easily - evaluateWithReason tells you exactly why an expression matched

Table of Contents


Installation

# npm
npm install json-expression-eval

# yarn
yarn add json-expression-eval

# pnpm
pnpm add json-expression-eval

Quick Start

import { evaluate } from 'json-expression-eval';

// Define your context (the data to evaluate against)
const context = {
  user: { age: 25, role: 'admin' },
  subscription: { plan: 'pro', daysLeft: 15 }
};

// Define your expression (can be stored as JSON!)
const expression = {
  and: [
    { 'user.age': { gte: 18 } },
    { 'user.role': 'admin' },
    { 'subscription.daysLeft': { gt: 0 } }
  ]
};

// Evaluate
const result = await evaluate(expression, context, {});
console.log(result); // true

Expression Syntax

Expressions are plain JavaScript objects that can be serialized to JSON. They support:

Logical Operators

| Operator | Description | Example | |----------|-------------|---------| | and | All conditions must be true | { and: [expr1, expr2] } | | or | At least one condition must be true | { or: [expr1, expr2] } | | not | Negates the condition | { not: expr } |

Comparison Operators

| Operator | Description | Example | |----------|-------------|---------| | eq | Equal (===) | { age: { eq: 25 } } | | neq | Not equal (!==) | { status: { neq: 'inactive' } } | | gt | Greater than | { price: { gt: 100 } } | | gte | Greater than or equal | { age: { gte: 18 } } | | lt | Less than | { quantity: { lt: 10 } } | | lte | Less than or equal | { score: { lte: 100 } } | | inq | In array | { color: { inq: ['red', 'blue'] } } | | nin | Not in array | { status: { nin: ['banned', 'suspended'] } } | | between | Between two values (inclusive) | { age: { between: [18, 65] as const } } | | regexp | Matches regex | { email: { regexp: '^.*@gmail\\.com$' } } | | regexpi | Matches regex (case-insensitive) | { name: { regexpi: '^john' } } | | exists | Check if value exists (not null/undefined) | { middleName: { exists: true } } |

Shorthand Syntax

For simple equality checks, you can omit the operator:

// These are equivalent:
{ userId: { eq: 'abc123' } }
{ userId: 'abc123' }

Nested Properties

Access nested properties using dot notation:

{ 'user.address.city': 'New York' }
{ 'order.items.0.price': { gt: 50 } }

Operators

Reference Values

Compare a property against another property in the context:

{
  'cart.total': {
    lte: { ref: 'user.balance' }  // cart.total <= user.balance
  }
}

Math Operations

Perform calculations in comparisons:

{
  'order.total': {
    lte: {
      op: '*',           // Multiply
      lhs: { ref: 'user.credit' },  // Left-hand side
      rhs: 0.9           // Right-hand side (10% discount)
    }
  }
}

Available operations: +, -, *, /, %, pow


Custom Functions

Add domain-specific logic with custom functions:

import { evaluate, Expression, EvaluatorFuncRunOptions } from 'json-expression-eval';

// Define your function table type
type MyFunctions = {
  isPremiumUser: (
    minPurchases: number,
    ctx: { purchases: number },
    opts: EvaluatorFuncRunOptions<{}>
  ) => Promise<boolean>;
};

// Implement the functions
const functions: MyFunctions = {
  isPremiumUser: async (minPurchases, ctx) => {
    return ctx.purchases >= minPurchases;
  }
};

// Use in expressions
const expression: Expression<MyContext, MyFunctions> = {
  and: [
    { isPremiumUser: 10 },  // Custom function call
    { 'subscription.active': true }
  ]
};

await evaluate(expression, context, functions);

Rule Engine

For more complex scenarios, use the rule engine to evaluate multiple rules and get detailed results:

import { RulesEngine, Rule } from 'json-expression-eval';

type MyPayload = { discountPercent: number };

const rules: Rule<MyPayload, ...>[] = [
  {
    condition: {
      and: [
        { 'user.tier': 'gold' },
        { 'cart.total': { gte: 100 } }
      ]
    },
    consequence: {
      message: 'Gold member discount applied!',
      custom: { discountPercent: 20 }
    }
  },
  {
    condition: { 'cart.total': { gte: 50 } },
    consequence: {
      message: 'Bulk discount applied!',
      custom: { discountPercent: 10 }
    }
  }
];

const engine = new RulesEngine(functions, ruleFunctions);
const results = await engine.evaluateAll(rules, context, {});
// Returns all matching rules with their consequences

API Reference

Core Functions

| Function | Description | |----------|-------------| | evaluate(expr, ctx, funcs, opts?) | Evaluate expression, returns boolean | | evaluateWithReason(expr, ctx, funcs, opts?) | Evaluate and return the minimal matching sub-expression | | validate(expr, ctx, funcs, opts?) | Validate expression structure against a context |

Classes

| Class | Description | |-------|-------------| | ExpressionHandler | Reusable expression evaluator instance | | RulesEngine | Rule engine for evaluating multiple rules |

evaluateWithReason Behavior

Returns { result: boolean, reason: Expression } where reason is the minimal sub-expression that determined the result:

  • or = true: Returns {or: [firstTrueExpr]}
  • or = false: Returns {or: [allExprs]} (all failed)
  • and = false: Returns {and: [firstFalseExpr]}
  • and = true: Returns {and: [allExprs]} (all passed)

Examples

For more examples, see the /src/examples and /src/test directories.


License

MIT - See LICENSE for details.