JsonLogic
- Links
- Play
- 📌 O que é JsonLogic
- 🧩 Estrutura básica
- 📊 Exemplos práticos
- JsonLogic and TypeScript
- 🚀 Pontos para explorar mais
- ⚡ Funções personalizadas no JsonLogic
- ‼️Adding a whole library
Links
Play
- apps/chat/src/app/json-logic/page.tsx
- Json Logic Engine
- JsonLogic Play
Exemplo:
Rule:Data:{ ">": [ { "var": "idade" }, 18 ] }Output:{ "idade": 17 }false
📌 O que é JsonLogic
- JsonLogic é uma forma padronizada de escrever regras e condições usando JSON.
- A ideia é representar expressões lógicas, matemáticas e funcionais em um formato serializável (JSON), que pode ser interpretado por diferentes linguagens.
- Assim, você separa a regra dos dados:
- A regra é um objeto JSON (imutável, descritivo).
- O dado/contexto é outro objeto JSON (variáveis, arrays, etc.).
- Um interpretador (engine JsonLogic) avalia a regra em cima do contexto.
🧩 Estrutura básica
{ "operação": [argumento1, argumento2, ...] }
📊 Exemplos práticos
// Exemplos:
{ ">": [5, 3] }
{ ">": [ { "var": "idade" }, 18 ] }
{ "idade": 20 } // contexto
// ➡️ Resultado: true (20 > 18)
// CONDICIONAL (if/else)
{
"if": [
{ ">": [ { "var": "idade" }, 18 ] },
"Maior de idade",
"Menor de idade"
]
}
{ "idade": 16 } // contexto
// ➡️ Resultado: "Menor de idade"
// ARRAYS
{ "max": [ { "var": "notas" } ] }
{ "notas": [7, 8.5, 6] } // contexto
JsonLogic and TypeScript
JsonLogic and TypeScript can be effectively integrated to define and execute rules with strong type safety and improved developer experience.
- JsonLogic in TypeScript:
- Using
json-logic-jsorjson-logic-engine: These are popular JavaScript libraries that parse and execute JsonLogic rules. They can be directly used within a TypeScript project. - Installation:
npm install json-logic-js
# or
npm install json-logic-engine - Basic Usage:
import jsonLogic from 'json-logic-js'; // or 'json-logic-engine'
const rule = {
"and": [
{ ">": [{ "var": "age" }, 18] },
{ "==": [{ "var": "country" }, "USA"] }
]
};
const data = { age: 25, country: "USA" };
const result = jsonLogic.apply(rule, data);
console.log(result); // true
- Using
- Type Definitions for JsonLogic:
@types/json-logic-js: This package provides TypeScript type definitions for the json-logic-js library, enabling type checking for your JsonLogic rules.- Installation:
npm install @types/json-logic-js --save-dev - Benefit: When defining your RulesLogic in TypeScript, the types will guide you in constructing valid JsonLogic structures and help catch errors during development.
- Defining Custom Operators with TypeScript:
- If you extend JsonLogic with custom operators, you can define their types in TypeScript to maintain type safety.
- Example (Conceptual):
interface MyCustomOperator {
"myCustomOp": [any, any]; // Define arguments for your custom operator
}
type MyRulesLogic = RulesLogic<MyCustomOperator>; // Extend the base RulesLogic with your custom operator
- In summary:
- By using the
json-logic-js(orjson-logic-engine) library along with its corresponding@typespackage, you can leverage JsonLogic's rule-based system within a TypeScript environment, benefiting from static type checking and enhanced code maintainability. When extending JsonLogic with custom operators, you can also define their types for comprehensive type safety.
- By using the
🚀 Pontos para explorar mais
- Custom operators: como registrar funções personalizadas além das nativas.
- Array helpers avançados (map, reduce, filter, all, some).
- Composição de regras: combinar várias pequenas regras em estruturas maiores.
- UI para edição: criar um editor visual de JsonLogic (drag & drop → JSON).
- Performance e caching em cenários de milhares de regras.
- Integração com JsonSchema para validar entrada antes da avaliação.
- Uso em tempo real (ex.: trading bot, automações IoT).
⚡ Funções personalizadas no JsonLogic
import jsonLogic from "json-logic-js";
// 1. Registrar operador customizado
jsonLogic.add_operation("percent_change", (current: number, previous: number) => {
if (previous === 0) return null;
return ((current - previous) / previous) * 100;
});
// 2. Criar regra usando esse operador
const regra = {
">": [
{ "percent_change": [ { "var": "precoAtual" }, { "var": "precoAnterior" } ] },
5
]
};
// 3. Avaliar com contexto
const contexto = { precoAtual: 110, precoAnterior: 100 };
const resultado = jsonLogic.apply(regra, contexto);
console.log(resultado); // true (variação foi 10%)
JsonLogic in JavaScript allows the addition of custom operators to extend its functionality beyond the built-in operations. This feature is available in versions 1.0.9 and later of the JavaScript implementation.
To add a custom operator, the jsonLogic.add_operation() method is used. This method takes two arguments:
- The operator's codename (string): This is the key used in the JsonLogic rule to represent the custom operation.
- The function that implements the operation: This function will be executed when the custom operator is encountered in a JsonLogic rule. It should accept the necessary arguments and return the result of the operation.
Example:
To add a custom "plus" operator that performs addition:
var jsonLogic = require('json-logic-js'); // Assuming json-logic-js is installed
var plus = function(a, b) {
return a + b;
};
jsonLogic.add_operation("plus", plus);
// Now, you can use the custom "plus" operator in your JsonLogic rules:
var rule = { "plus": [10, 32] };
var data = {}; // No specific data needed for this example
var result = jsonLogic.apply(rule, data);
console.log(result); // Output: 42
In this example, the plus function is defined to perform addition. This function is then registered with JsonLogic under the codename "plus" using add_operation. Subsequently, any JsonLogic rule containing {"plus": [...]} will invoke this custom function with the provided arguments.
# ‼️ Adding a whole library
You can also import a whole library, and use its methods with dot-notation:
```js
jsonLogic.add_operation("Math", Math);
//Note the empty array for no arguments
jsonLogic.apply({"Math.random":[]}); //Returns a float between 0 and 1
jsonLogic.apply({"Math.abs":-42}); //Returns 42
jsonLogic.apply({"Math.ceil":41.001}); //Returns 42
jsonLogic.apply({"Math.log":1739274941520497700}); //Returns 42