Menu

#135 Can't parse string containing function (x)

v1.0 (example)
open
aalmiray
None
5
2020-11-08
2015-01-15
Ken Weiner
No

The following valid JSON string fails to parse:

{
  "myarray" : ["function (x)"]
}

Example code:

String json = "{\"myarray\" : [\"function (x)\"]}";
JSONObject result = JSONObject.fromObject(json);

This results in the following stacktrace:

java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.substring(String.java:1958)
    at net.sf.json.JSONArray._fromJSONTokener(JSONArray.java:1167)
    at net.sf.json.JSONArray.fromObject(JSONArray.java:125)
    at net.sf.json.util.JSONTokener.nextValue(JSONTokener.java:351)
    at net.sf.json.JSONObject._fromJSONTokener(JSONObject.java:1008)
    at net.sf.json.JSONObject._fromString(JSONObject.java:1201)
    at net.sf.json.JSONObject.fromObject(JSONObject.java:165)
    at net.sf.json.JSONObject.fromObject(JSONObject.java:134)

If you simply change the word "function" to any other string or remove one of the parentheses, it parses fine.

JSONObject result = JSONObject.fromObject(json);

Discussion

  • Uriel Ben-Iohanan

    I got the same exception with even a simpler JSON:

    {
      "key": "function (a)"
    }
    

    I use a vanilla 2.4 release of JSON-lib.

     
  • aalmiray

    aalmiray - 2020-11-08

    Development of this library has been moved to GitHub since 2010, please report any issues you may find at https://github.com/kordamp/json-lib/issues

     

Log in to post a comment.