如何在JSON对象上实现可动态调整的条件判断逻辑?
Hey there! Let's figure out how to implement dynamic condition checks on your JSON object. I’ve worked through similar problems before, so here are a few practical approaches you can take:
eval() (Quick but Security-Conscious) If your condition strings come from a fully trusted source (like internal system configurations, not user input), eval() is the fastest way to get this done. You just need to map the placeholder in your condition string (like inputFromAPI) to your actual jsonObject variable, then run the evaluation.
Example code:
// Your parsed JSON object const jsonObject = { DidWeCharge: true, DidWeHold: false }; // Your dynamic condition string const conditionStr = "inputFromAPI.DidWeCharge == true && inputFromAPI.DidWeHold == false"; // Swap the placeholder with your variable name const executableCondition = conditionStr.replace("inputFromAPI", "jsonObject"); // Run the condition check const result = eval(executableCondition); // Returns true here
Important note: Never use eval() with untrusted input—it executes arbitrary code, which is a massive security risk. Only use this if you’re 100% in control of where the condition strings come from.
If your conditions might come from external sources, or you want to avoid the risks of eval(), dedicated expression parsing libraries are the way to go. They’re designed to safely evaluate logical expressions without executing arbitrary code.
Two popular options are expr-eval (great for string-based expressions) and json-logic-js (uses JSON-structured conditions). Here’s how to use both:
With expr-eval:
First install the library (for Node.js):
npm install expr-eval
Then implement the check:
const { Parser } = require('expr-eval'); const jsonObject = { DidWeCharge: true, DidWeHold: false }; // Parse your condition string into an executable expression const parser = new Parser(); const expression = parser.parse("DidWeCharge == true && DidWeHold == false"); // Evaluate against your JSON object const result = expression.evaluate(jsonObject); // Returns true
With json-logic-js:
Install the library first:
npm install json-logic-js
Then use JSON-structured conditions (you can also convert your string condition to this format if needed):
const jsonLogic = require('json-logic-js'); const jsonObject = { DidWeCharge: true, DidWeHold: false }; // Define your condition in JSON logic format const condition = { "and": [ { "==": [{"var": "DidWeCharge"}, true] }, { "==": [{"var": "DidWeHold"}, false] } ] }; // Apply the condition to your JSON object const result = jsonLogic.apply(condition, jsonObject); // Returns true
If your conditions follow a strict, simple pattern (only basic operators like ==, !=, &&, ||), you can build your own lightweight parser. This gives you full control without relying on external libraries.
Example implementation:
const jsonObject = { DidWeCharge: true, DidWeHold: false }; const conditionStr = "inputFromAPI.DidWeCharge == true && inputFromAPI.DidWeHold == false"; // Split the condition into individual checks (handles && first here) const individualConditions = conditionStr.split("&&").map(cond => cond.trim()); let allConditionsMet = true; for (const cond of individualConditions) { // Split each condition into property, operator, expected value const [propPart, operator, valuePart] = cond.split(/\s+/); // Extract the actual property name from the placeholder const propName = propPart.replace("inputFromAPI.", ""); const actualValue = jsonObject[propName]; // Parse the expected value into the correct data type let expectedValue; if (valuePart === "true") expectedValue = true; else if (valuePart === "false") expectedValue = false; else if (!isNaN(valuePart)) expectedValue = Number(valuePart); else expectedValue = valuePart.replace(/['"]/g, ""); // Remove quotes for string values // Check the condition against the operator switch(operator) { case "==": if (actualValue !== expectedValue) allConditionsMet = false; break; case "!=": if (actualValue === expectedValue) allConditionsMet = false; break; // Add more operators like >, < as needed } } console.log(allConditionsMet); // Outputs true
This approach requires handling edge cases (like quoted strings or different data types), but it’s perfect if you need a lightweight, self-contained solution.
内容的提问来源于stack exchange,提问作者Richard

