Error parsing empty json array with nashorn

276 views Asked by At

I'm using Oracle JDK 1.8.0_65 with nashorn to run some test cases and I found a very strange behavior when parsing an empty JSON Array.

Here's the code i'm running in nashorn:

var testCase = {
    start:function() {
        // Case 1: a initialized from JavaScript Array
        var a = [];
        this.log.debug("a before:" + JSON.stringify(a) + " (length:" + a.length + ")");
        a.push(15);
        this.log.debug("a after:" + JSON.stringify(a) + " (length:" + a.length + ")");

        // Case 2: b initialized parsing a JSON Array
        var b = JSON.parse("[]"); 
        this.log.debug("b before:" + JSON.stringify(b) + " (length:" + b.length + ")");
        b.push(15);
        this.log.debug("b after:" + JSON.stringify(b) + " (length:" + b.length + ")");
    }
};

and the output is:

a before:[] (length:0)
a after:[15] (length:1)
b before:[] (length:0)
b after:[0,15] (length:2)

I'ts look like a bug in nashorn JSON parser. Returned Array is not really an empty Array, but it's look like that before pushing the first element. There's a hidden "0" that appears after the first push.

Can't find any bug report about this behavior. Am I using JSON.parse in a wrong way?

Thanks. J

1

There are 1 answers

0
A. Sundararajan On BEST ANSWER

Your usage is correct. It seems to be a bug and it appears to have been fixed. I just tried 1.8.0_112. It works as expected.