Looked all around the internet for a java port of a reliable json comment stripper and minifier, but most were flawed designs (not supporting multiline comments, or comment patterns within strings).
So in my haste, I went and threw this together: https://gist.github.com/justisr/abab012af3ef399908798a687185d49a
Gave it a test on an existing json file I had, and everything came out as expected, but I'm not satisfied. Is there really no faster/standard means of stripping comments from a json string?
Previously I was using https://github.com/getify/JSON.minify but it was slow and again, a regular // comment at the end of the file broke it, hence my desperation.
Simplest thing would be to run your JSON through Jackson:
public static String removeComments(String json) throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.enable(JsonParser.Feature.ALLOW_COMMENTS);
return mapper.writeValueAsString(mapper.readTree(json));
}
If you wanted to get fancier, you could use Jackson's streaming API to avoid buffering the document in memory, but unless your documents are large or performance is absolutely critical, that's probably overkill.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With