Search code examples
javajavascriptrhino

Parsing Javascript in Java, Javascript Objects


I am trying to parse a Javascript file using ScriptEngine in Java. I am not interested in executing scripts, just parsing it to get some values.

The script files are comprised of a series of arrays with this structure:

var array= new Array();
array[0]=new Array();
array[0]['point']=new Point2D(2.454,-8.33);
array[0]['name']='Object 1';
array[1]=new Array();
array[1]['point']=new Point2D(42.84, 3.53);
array[1]['name']='Object 2';

...

with Point2D defined as:

function Point2D(x,y) {
this.x = x;
this.y = y;
}

So far I've parsed the script with this code:

ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine se = mgr.getEngineByName("JavaScript");
try {
  se.eval(file);
  NativeArray array = (NativeArray)se.get("array");
  for(int i = 0; i < array.getLength(); i++){
    if(array.get(i)!=null){
      NativeArray elementArray = (NativeArray)array.get(i);
      System.out.println("Object: " + elementArray);
      System.out.println("name: " + elementArray.get("name", elementArray));
      System.out.println("point: " +  elementArray.get("point", elementArray));
    }
  }
}
catch (ScriptException e) {
      ....
}

Which gives me the name properly, but I get an instance of Object class for the Point2D item. Since it was originally a javascript object, how can I parse it to obtain x and y values?


Solution

  • You could do it like this:

        NativeObject point;
        NativeArray elementArray;
        for(int i = 0; i < array.getLength(); i++){
            if(array.get(i)!=null){
                elementArray = (NativeArray)array.get(i);                
                System.out.println("name: " + elementArray.get("name", elementArray));
                point = (NativeObject) arrayFirstElement.get("point", arrayFirstElement);
                //System.out.println("point.x: " +  NativeObject.getProperty(point, "x"));
                //System.out.println("point.y: " +  NativeObject.getProperty(point, "y"));
                System.out.println("object point has: ");
                for ( Object propertyId : NativeObject.getPropertyIds(point)){
                    System.out.println("property "+ propertyId + " has value " + NativeObject.getProperty(point, propertyId.toString()));
                } 
            }
        }
    

    But take a look at these tutorials: 1 ,2, you might get some fresh ideas :)