Skip to content

Solution for array.length in JAVA #57

Description

@backtrackshubham

HI Team, thanks for creating a wonderful library, kudos to everyone in the team,

I am facing a problem, so I am using json-logic-java and on the online playground the following rule works fine,

data  => {arr: [1,2,3,4]}

rule => "{\"*\": [{\"var\": \"arr.length\"}, 5]}";

// output as 20

But when I am trying to use the same I java code it throws some error, like number format

// Below code fails
   JsonLogic jsonLogic = new JsonLogic();

// Set up some JSON and some data.
    String expression = "{\"*\": [{\"var\": \"arr.length\"}, 5]}";
    Map<String, Object> data = new HashMap<>();
    data.put("x", 10);
    data.put("arr", asList(1, 2, 3, 4, 5));

// Evaluate the result.
    double result = (double) jsonLogic.apply(expression, data);
    assert result == 20.0;
  }

I have made a workaround for this following the docs but I was wondering if there is a cleaner way to achieve the same, below is the work around

    JsonLogic jsonLogic = new JsonLogic();

// Set up some JSON and some data.
    String expression = "{\"*\": [{\"var\": \"arrLength\"}, 5]}";
    Map<String, Object> data = new HashMap<>();
    data.put("x", 10);
    data.put("arr", asList(1, 2, 3, 4, 5));
    List<Map<String, Object>> selectedItems = (List<Map<String, Object>>) data.get("arr");
   // Putting the value for size
    data.put("arrLength", selectedItems.size());

// Evaluate the result.
    double result = (double) jsonLogic.apply(expression, data);
    assert result == 25.0;
  }

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions