JSON source information

Primitive Types

The advantage of this library is that each primitive JSON value (string, number, boolean, null) hold where it originates from. To obtain that information, call token().

JSONValueString jsStr = ...;
JSONToken token = jsStr.token();

An instance of JSONToken holds following information.

  • beginningLocation() returns an object which holds the line and column number of the first character of this JSON value within the JSON text.
  • endLocation() returns an object which holds the line and column number of the character of the last character of this JSON value within the JSON text.
  • source() returns an instance of JSONText from which the parser extracted the JSON value.
  • JSONText#name() holds the short name of the JSON text. In many cases, it returns a file name.
  • JSONText#uri() holds the URI of the JSON text.
JSONValue root =
    JSONText.fromString("{\"key1\": 1.23, \"key2\": \"te\\nst\" }").parse().root();

JSONValueObject rootObj = (JSONValueObject) root;
JSONValueString str = (JSONValueString) rootObj.get("key2");
JSONToken token = str.token();

System.out.println("Token: " + token.text());
System.out.println(
    String.format(
        "Start: line %d, column %d",
        token.beginningLocation().line(),
        token.beginningLocation().column()));
System.out.println(
    String.format(
        "End  : line %d, column %d",
        token.endLocation().line(),
        token.endLocation().column()));

Structured Types

Structured values (array and object) also hold the source information. by calling begin() and end(). Those methods basically return the token informaiton about {, }, [ and ].

JSONValue root =
    JSONText.fromString("{\"key1\": [true, 123]}").parse().root();
JSONValueObject rootObj = (JSONValueObject) root;

JSONToken begin = rootObj.begin();
JSONToken end = rootObj.end();

String msgBegin =
    String.format(
        "%s at line %d, column %d",
        begin.text(),
        begin.beginningLocation().line(),
        begin.beginningLocation().column());
System.out.println(msgBegin);

String msgEnd =
    String.format(
        "%s at line %d, column %d",
        end.text(),
        end.beginningLocation().line(),
        end.beginningLocation().column());
System.out.println(msgEnd);
Warning

token(), begin() and end() return null if the JSON value does not originate from an instance of JSONText.

For example, if your application creates new instances of JSON values to generate a new JSON text, they do not hold a source information.