2

I have this JavaScript file:

var input = {
  "CONTRATE": 0,
  "SALINC": 0,
  "RETAGE": 55.34,
  "MARSTATUS": "single",
  "SPOUSEDOB": "1970-01-01",
  "VIEWOPTION": "pension"
};

var inputValidation = "input.CONTRATE > 50 && input.SALINC < 50 && input.RETAGE > 50";

eval(inputValidation);

How to get JSON value of "input" variable using JINT as JSON object string?

user3473830
  • 7,165
  • 5
  • 36
  • 52
monstro
  • 6,254
  • 10
  • 65
  • 111

1 Answers1

5

I believe we can achieve desired result in 3 ways

Method 1 - Use Jint's Built-in Parser

Jint has built-in parser to support JSON.parse and JSON.stringify functions for javascript. we can use them for this task:

        var engine =new Engine();

        var json = @"{
              ""CONTRATE"": 0,
              ""SALINC"": 0,
              ""RETAGE"": 55.34,
              ""MARSTATUS"": ""single"",
              ""SPOUSEDOB"": ""1970-01-01"",
              ""VIEWOPTION"": ""pension""
            }";

        var input = new JsonParser(engine).Parse(json);

        var result= engine
            .SetValue("input", input)
            .Execute("input.CONTRATE > 50 && input.SALINC < 50 && input.RETAGE > 50")
            .GetCompletionValue().AsBoolean();

Method 2 - Use 3rdParty Json Serializer

Jint accepts POCO objects as input, hence we can first convert a json to POCO then feed it to Jint for results (for this example, I used Json.net as a Deserializer)

        var input = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
        var result= engine
            .SetValue("input", input)
            .Execute("input.CONTRATE > 50 && input.SALINC < 50 && input.RETAGE > 50")
            .GetCompletionValue().AsBoolean(); 

Method 3 - Put JSON object in evaluation script

Or as Mr.Ros (author of Jint) suggested we can put JSON object and condition in the same script and pass it to Jint for evaluation.

        var engine = new Engine();

        var js = @"
         input={
          ""CONTRATE"": 0,
          ""SALINC"": 0,
          ""RETAGE"": 55.34,
          ""MARSTATUS"": ""single"",
          ""SPOUSEDOB"": ""1970-01-01"",
          ""VIEWOPTION"": ""pension""
        };

        input.CONTRATE > 50 && input.SALINC < 50 && input.RETAGE > 50;";

        var result = engine
            .Execute(js)
            .GetCompletionValue().AsBoolean();
user3473830
  • 7,165
  • 5
  • 36
  • 52
  • 1
    You can also paste the JSON object directly in the script with the condition. It will be evaluated as an object inside the script. Or if it is passed as a string, use `JSON.parse` instead of doing it from C#. – Sébastien Ros - MSFT Oct 19 '15 at 21:33
  • JSONParser does not work when JSON has Space in the key names. Like { "First Name" : "Test"}> Is there a way to handle this ? – Praneet Nadkar May 02 '23 at 06:57