Home > OS >  Evaluate JSON object with expression with variable name
Evaluate JSON object with expression with variable name

Time:12-29

We need to evalue json object expression in java

we have following source json object

{
  "model":"abc",
  "variant":"m1",
  "stage":2,
  "a":100,
  "b":200,
  "display name":"${model}-${variant}",
  "c":"${a}*${b}",
  "description":"${model}-${variant}-${stage*10}"
}

after evaluation the json object should be like

{
  "model":"abc",
  "variant":"m1",
  "stage":2,
  "a":100,
  "b":200,
  "display name":"abc-m1",
  "c":"300",
  "description":"abc-m1-20"
}

expression can be of 3 types

  1. Pure arithmetic expression
  2. concat strings
  3. combination of concat and arithmetic expression

We are open to any modification in source json to define expression representation

Regards, Pranav

we tried https://github.com/json-path/JsonPath but that is more of a filtering json

CodePudding user response:

The latest version 1.4.2 of Josson added function eval().

https://github.com/octomix/josson

Josson josson = Josson.fromJsonString(
    "{"  
    "  \"model\": \"abc\","  
    "  \"variant\": \"m1\","  
    "  \"stage\" :2,"  
    "  \"a\": 100,"  
    "  \"b\": 200,"  
    "  \"display name\": \"concat(model,'-',variant)\","  
    "  \"c\": \"round(calc(a b),0).toText()\","  
    "  \"description\": \"concat(model,'-',variant,'-',round(calc(stage*10),0))\""  
    "}");
JsonNode node = josson.getNode(
    "field(display name: eval(display name),"  
    "      c: eval(c),"  
    "      description: eval(description))");
System.out.println(node.toPrettyString());

Output

{
  "model" : "abc",
  "variant" : "m1",
  "stage" : 2,
  "a" : 100,
  "b" : 200,
  "display name" : "abc-m1",
  "c" : "300",
  "description" : "abc-m1-20"
}
  • Related