1

Is it possible to use JSON.parse in Java Nashorn with Java 8? I haven't been able to find anything clear on the subject. I have read that when using JDK9 native json functionality is included but I am using 1.8.

json

[{ "user":"dave", "value":"accounting"},{ "user":"sara", "value":"research"}]

i am invoking a function written in the js

Invocable invocable = (Invocable) engine;
invocable.invokeFunction("myFunc", json);

javascript

var myFunc = function(json) {
    // the json is input from elsewhere I want to be able to JSON.parse this or use a FileWriter and write it back out to a file as json
    JSON.parse(json);

    var f = new File("C:\\output", "log.log");
    var writer = new FileWriter(f, true);

 // problem is it only sees it as a string and doesn't write it like json
    writer.write(JSON.stringify(json));
    writer.write("\r\n");
    writer.close();

}

I want to be able to pass the json from elsewhere into the nashorn js function myFunc, but write it to a file as json. It seems it gets turned into a java object and there is no JSON.parse in this context? Is that correct? Perhaps I am going about this wrong, any advice is appreciated.

Justin
  • 4,461
  • 22
  • 87
  • 152
  • You seem to be confusing JavaScript and Java. For Java, you could use something like Gson (from Google) for manipulating JSON data. See -> https://mvnrepository.com/artifact/com.google.code.gson/gson – daddygames May 14 '19 at 17:20
  • JavaScript is a client-side scripting language. Java is a server-side programming language. They are not the same thing. See -> https://stackoverflow.com/questions/245062/whats-the-difference-between-javascript-and-java – daddygames May 14 '19 at 17:22
  • 2
    @daddygames I believe I mentioned/tagged this is in the context of Java Nashorn – Justin May 14 '19 at 17:26
  • Doh! I overlooked that tag and in the title. My bad. I am unfamiliar with Nashorn. A search leads me to warnings of it being deprecated in Java 11, if that matters. If you are able to access standard Java libraries, Gson or a similar library may still be the way to go. Good luck! – daddygames May 14 '19 at 19:24
  • @daddygames no worries. thanks – Justin May 14 '19 at 19:26

0 Answers0