Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
清除内存中格式错误的json的最常用方法_Json_Groovy - Fatal编程技术网

清除内存中格式错误的json的最常用方法

清除内存中格式错误的json的最常用方法,json,groovy,Json,Groovy,在处理一些json文件时,遇到了一些包含c风格注释的格式错误的文件。假设我没有这些文件的所有权,并且无法更改它们,我需要以自动化的方式分析json数据。JsonSlurper在看到这些注释时会死掉,因此我编写了一个方法来删除这些有问题的行: def filterComments(String raw){ def filtered = "" raw.eachLine { line -> def tl = line.trim() if(!(tl.

在处理一些json文件时,遇到了一些包含c风格注释的格式错误的文件。假设我没有这些文件的所有权,并且无法更改它们,我需要以自动化的方式分析json数据。JsonSlurper在看到这些注释时会死掉,因此我编写了一个方法来删除这些有问题的行:

def filterComments(String raw){
    def filtered = ""
    raw.eachLine { line ->
        def tl = line.trim()
        if(!(tl.startsWith("//") || tl.startsWith("/**") || tl.startsWith("*"))){
            filtered += line;}}
    return filtered;
}
我非常喜欢Groovy,并把它作为我的维护工具,但我不是“最Groovy”的开发人员,这就是一个例子。我想用一种更棒的方式来实现这一点

一些附加说明:这是作为脚本运行的。如果有一种方法可以让JsonSlurper忽略注释而不是使用这个实用方法,那么这个解决方案将被认为更有价值。提前谢谢

我的看法:

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

这里有一种方法:

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();'

这将删除以
/*
*
开头的任何行,以及
/

之后的任何行。这不会为我过滤任何注释。效果更好,但会错过将正则表达式更改为
/^\s*(\*\/\*\/\/\/\/\/\/code>应选择
/*
。因此该行将是
str.readLines()。findAll{!(it=~/^\s*(\*\/\*\\/\*\/\/).*/)}。join('\n')
@md\u rasler它之所以会错过
/*
,只是因为你的代码也会错过它。我只是重新表述了你的代码;-)