Reputation: 6640
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?
Upvotes: 2
Views: 4349
Reputation: 7285
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();
Upvotes: 5