Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use JSONata in Java?

Tags:

java

json

JSONata is an expression language designed to query and transform JSON data structures.

I find that current implementations of JSONata are in Javascript only. (https://github.com/jsonata-js/jsonata)

I want to use JSONata in my Java code. It'll make life much easier to manipulate JSON documents in Java.

A possible way could be to use the standard Java classes under javax.script package to interact with the Javascript-based JSONata implementation.

Has anyone already done this? Is there any sample code to demonstrate how this can be achieved?

Has anyone implemented other mechanisms of using JSONata in Java?

like image 983
Joy Patra Avatar asked Jul 12 '26 18:07

Joy Patra


1 Answers

The following snippet shows how you could invoke the JSONata processor from Java using the embedded JavaScript engine...

ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
Invocable inv = (Invocable) engine;
FileReader jsonata = new FileReader("jsonata.js");

// load the JSONata processor
engine.eval(jsonata);

// read and JSON.parse the input data
byte[] sample = Files.readAllBytes(Paths.get("sample.json"));
engine.put("input", new String(sample));
Object inputjson = engine.eval("JSON.parse(input);");

// query the data
String expression = "$sum(Account.Order.Product.(Price * Quantity))";  // JSONata expression
Object expr = inv.invokeFunction("jsonata", expression);
Object resultjson = inv.invokeMethod(expr, "evaluate", inputjson);

// JSON.stringify the result
engine.put("resultjson", resultjson);
Object result = engine.eval("JSON.stringify(resultjson);");
System.out.println(result);

In this example, the jsonata.js file has been pulled down from the JSONata GitHub repo as well as the 'Invoice' sample code from try.jsonata.org.

Extra code would be needed to handle errors, but this gives the general idea.

like image 98
Andrew Coleman Avatar answered Jul 15 '26 09:07

Andrew Coleman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!