Search code examples
javascriptjavajsonrhino

How to pass parsed JSON to a JavaScript function with Rihno (Java)?


I am using Rhino to invoke a JavaScript makeQuery(hints) function in Java.

I have a String that contains JSON and I want to pass it as parameter to a JavaScript function. The way I am currently doing is that I pass the string and then parse it in the JavaScript function. However, I don't want to have to parse it in the function i.e. I want it already parsed.

Here is my code handling calling the JavaScript function:

Context context = Context.enter();
try {
    // rawJSON is the string that contains the JSON. hints is the parsed JSON I want.
    var hints = Context.javaToJS(rawJSON, context.initStandardObjects());

    ScriptableObject scope = context.initStandardObjects();
    // script is a string containing the code of the JavaScript function.
    context.evaluateString(scope, script, "script", 1, null);
    Function makeQuery = (Function) scope.get("makeQuery", scope);

    // hints here is passed as a String, but I want it passed as a native JSON
    Object result = makeQuery.call(context, scope, scope, new Object[]{hints});
    return (String) Context.jsToJava(result, String.class);
} finally {
    Context.exit();
}

And here is the JavaScript function:

function makeQuery(rawHints) {
    // I don't want to have to do this. I want it to arrive already parsed.
    const hints = JSON.parse(rawHints);
    return `From the hints below, generate a 1500 to 3000 words article.\n
Hints:
Title: ${hints.title}
Description: ${hints.description}
Tags: ${hints.tags.join(",")}\\n
    `
}

What I tried

I tried to parse hints to a NativeObject but it returns the exception that it can't convert NativeJavaObject to NativeObject.


Solution

  • The solution is to use the NativeJSON.parse method. This is how I did it:

    var hints = NativeJSON.parse(context, scope, rawJSON, (context1, scriptable, scriptable1, objects) -> objects[1]);