4

In my current project I have to read a JavaScript file from the web and extract an object from it. The variable can vary from time to time, so I have to read it instead of hard coding it into my android app.

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

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

I have a problem with this. Do I have to implement some compiler-like scanner just to look for the name and get its value, or there is some existing tool I can use?

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

3
  • 2
    Try Rhino Commented Nov 5, 2012 at 13:09
  • A much better way would be to store the data in JSON format on the server. Loading of JSON data is in the JavaScript/web browser as simple as in Java. Commented Nov 5, 2012 at 13:16
  • @Cthulhu nice suggestion, but it crashes since the js is for browser Commented Nov 6, 2012 at 8:37

2 Answers 2

1

There are many libraries in Java to parse the JSON. There is a list on JSON.org

Read the file with Java

import org.json.JSONObject;

URL url = new URL("http://example.com/foo.js");
InputStream urlInputStream = url.openStream();
JSONObject json = new JSONObject(urlInputStream.toString());  
Sign up to request clarification or add additional context in comments.

2 Comments

I know how to parse it. I am asking how to get it.
Make a http request, your question says nothing about reading it. lol
0

Finally code it myself.

//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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.