Skip to content

parseJSONObject() and parseJSONArray() do not return null when parsing fails #165

@processing-bot

Description

@processing-bot

Created by: denezth

Description

Both parseJSONObject() and parseJSONArray() throw a RuntimeException if the provided JSON String is not valid.

Expected Behavior

The documentation states:

If the String does not contain JSONObject data or cannot be parsed, a null value is returned.

Both functions should therefore return null in the event of a parsing error. This would not prevent the stackTrace from being displayed in console so that the user can understand the reason.

Steps to Reproduce

  1. Pass an invalid JSON String to either parseJSONObject() or parseJSONArray()
JSONObject object = parseJSONObject("invalidJSONString");

println(object);
  1. Run the sketch. A RuntimeException is thrown, stopping execution unless we use a try..catch.

My Environment

  • Processing version: 4.0a3
  • Operating System and OS version: MacOS 10.14.6

Possible Solution

In PApplet.java, we could catch the RuntimeException inside the parseJSONObject/Array(). Something like this:

public JSONObject parseJSONObject(String input) {
  try {
    return new JSONObject(new StringReader(input));
  } catch (RuntimeException e) {
    e.printStackTrace();
    return null;
  }
}

I will open a pull request.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions