简体   繁体   中英

How to get JSON value from Javascript using JINT library

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?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM