The cleanest way to clear garbled json in memory

Working with some json files, encountered some incorrect ones, with c style comments included. Suppose I do not have rights to these files, and changing them is not an option, I need to analyze the json data automatically. JsonSlurper dies when it sees these comments, so I wrote a line removal method:

def filterComments(String raw){
    def filtered = ""
    raw.eachLine { line ->
        def tl = line.trim()
        if(!(tl.startsWith("//") || tl.startsWith("/**") || tl.startsWith("*"))){
            filtered += line;}}
    return filtered;
}

I really like Groovy and turned to him as my choice of maintenance tool, but I'm not the Grooviest developer, this is an example. I would like a more groovy way to accomplish this.

Some additional notes: this runs as a script. If there is a way to make JsonSlurper ignore comments instead of using this utility method, this solution will be considered more valuable. Thanks in advance!

+4
source share
2 answers

Here is one way to do this:

def json = '''
// A comment
Foo f = new Foo(); // this is a comment
/*
* Multiline comment
*
*/
'''

def filterComments(str) {
    str?.replaceAll(/(\/\/|\/\*|\*).*\n?/, '')?.trim()
}

assert filterComments(json) == 'Foo f = new Foo();'

This will delete any line starting with /*or *, as well as after //.

+3
source

My welcome:

def filterComments(str){
    str.readLines().findAll{ !(it ==~ /^\s*(\*|\/\*\*|\/\/).*/) }.join('\n')
}
+3
source

Source: https://habr.com/ru/post/1530649/


All Articles