How can I get the value of a Javascript variable in Java?

In my current project, I have to read a JavaScript file from the Internet and extract an object from it. The variable may change from time to time, so I should read it, and not hardcode it into my Android application.

Let's say I want to extract the following variable (and after that parse the string using JSONObject, which is trivial):

var abc.xyz = { "a": {"one", "two", "three"}, "b": {"four", "five"} } 

I have a problem with this. Should I implement some kind of scanner that looks like a compiler, only to search for a name and get its value, or is there some existing tool that I can use?

The JavaScript file is not as simple as this example. It contains a lot of other code. Therefore simple new JSONObject() or something will not do.

+4
source share
2 answers

Java has many libraries for parsing JSON. List on JSON.org

Read Java file

 import org.json.JSONObject; URL url = new URL("http://example.com/foo.js"); InputStream urlInputStream = url.openStream(); JSONObject json = new JSONObject(urlInputStream.toString()); 
+2
source

Finally encode it.

 //remove comments private String removeComment(String html){ String commentA = "/*"; String commentB = "*/"; int indexA, indexB; indexA = html.indexOf(commentA); indexB = html.indexOf(commentB); while(indexA != -1 && indexB != -1 ){ html = html.substring(0, indexA) + html.substring(indexB + commentB.length()); indexA = html.indexOf(commentA); indexB = html.indexOf(commentB); } return html; } //find variable with name varName private String findVar(String varName, String html, char lBrace, char rBrace){ String tmp = html.substring(html.indexOf(varName)); tmp = tmp.substring(tmp.indexOf(lBrace)); int braceCount = 0; int index = 0; while(true){ if(tmp.charAt(index) == lBrace){ braceCount ++; }else if(tmp.charAt(index) == rBrace){ braceCount --; } index ++; if(braceCount == 0){ break; } } return tmp.substring(0, index); } 
0
source

Source: https://habr.com/ru/post/1444112/


All Articles