Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest means of removing comments from JSON in java?

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.

like image 943
justis Avatar asked Sep 18 '18 21:09

justis


1 Answers

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.

like image 173
dnault Avatar answered Oct 29 '22 00:10

dnault