I'm dealing with systems which manipulate "relaxed" JSON data which includes shell-style #
line comments:
[
{
# Batman
"first-name": "Bruce",
"last-name": "Wayne"
},
{
# Superman
"first-name": "Clark",
"last-name": "Kent"
}
]
The part of the system I'm working on uses json-lib - which I'm surprised to discover is tolerant of the shell-style comments - to parse the JSON input.
I need to extract some additional annotation from those comments, but json-lib seems to just discard them without providing an API for reading them:
JSONObject map = (JSONObject)JSONSerializer.toJSON("{\n"+
" # Batman\n" + // note the shell-style # comment
" \"first-name\": \"Bruce\",\n" +
" \"last-name\": \"Wayne\"\n" +
"}");
System.out.println(map.toString());
/* <<'OUTPUT'
* {"first-name":"Bruce","last-name":"Wayne"}
* OUTPUT
* note the absence of the shell-style comment
*/
This makes sense since comments aren't part of the JSON spec and I'm lucky json-lib doesn't just choke when parsing them in the first place.
Of note:
- other systems consume this same JSON and the annotations need to be transparent to them, so the JSON structure can't be modified by adding properties for the comments instead.
- not all the components and objects in my system have access to the raw JSON source: one component reads the file and parses it using JSONlib and passes de-serialized maps etc around.
How can I read and parse these comments while processing the JSON input? Is there a library which will allow me to read them and relate them to their position in the JSON - can I easily connect the Batman
comment to the "Bruce Wayne" entry?
I'm currently using json-lib, but I'm open to investigating other JSON libraries and equally open to using other languages which extend JSON, such as YAML - but I'm not sure those tools will allow me to read and process the comments in my input.