groovy 使用正则表达式(或JSONSlurper?)过滤JSON输出

qmelpv7a  于 2022-11-01  发布在  其他
关注(0)|答案(2)|浏览(215)

尝试通过使用以下脚本来实现这一点,我想用一个循环来扩展它,以循环通过输入。这应该过滤具有值“valse”的对象,其他的应该被删除/替换。

def Message processData(Message message) {

    //getBody & new jsonSlurper
    def body = message.getBody(java.lang.String) as String
    def data = new JsonSlurper().parseText(body)

    if (data.value != "false") {
        body = body.replaceAll(~/^(.*?)\childNodes/, "")
        message.setBody(body);
    } else {
    }
    return message
}

输入:

[{
    "name": "1",
    "value": "true",
    "childNodes": [{
        "name": "2",
        "value": "true",
        "childNodes": [{
            "name": "3",
            "value": "false",
            "childNodes": [{
                "name": "4",
                "value": "false"
            }]
        }]
    }]
}]

所需输出:

[{
        "name": "3",
        "value": "false",
        "childNodes": [{
            "name": "4",
            "value": "false"
        }]
    }]
esyap4oy

esyap4oy1#

import groovy.json.*

def body ='''
[{
    "name": "1",
    "value": "true",
    "childNodes": [{
        "name": "2",
        "value": "true",
        "childNodes": [{
            "name": "3",
            "value": "false",
            "childNodes": [{
                "name": "4",
                "value": "false"
            }]
        }]
    }]
}]
'''

def filter(arr){
    for(i in arr){
        if(i.value == 'false') return [i]
        def filteredChild = filter(i.childNodes)
        if(filteredChild)return filteredChild
    }
    return null // not found
}

def filtered = filter( new JsonSlurper().parseText(body) )
println new JsonBuilder(filtered).toPrettyString()
ghg1uchk

ghg1uchk2#

假设您每次只有一个子对象,并且您的任务是查找第一个value=false节点并将其与所有子节点一起返回,则可以执行以下操作:

def processData(String message) {
    def data = new JsonSlurper().parseText(message)[0]
    while (data.value != 'false') { data = data.childNodes[0] }
    return new JsonBuilder([data]).toPrettyString()
}

下面是一个Spock测试(用常规的json字符串替换了pretty字符串,这样就更容易用==来比较字符串)

class ParseSpec extends Specification {
    def testString = '''
    [{
        "name": "1",
        "value": "true",
        "childNodes": [{
            "name": "2",
            "value": "true",
            "childNodes": [{
                "name": "3",
                "value": "false",
                "childNodes": [{
                    "name": "4",
                    "value": "false"
                }]
            }]
        }]
    }]
    '''

    def processData(String message) {
        def data = new JsonSlurper().parseText(message)[0]
        while (data.value != 'false') { data = data.childNodes[0] }
        return JsonOutput.toJson([data])
    }

    def 'run test'() {
        expect:
        '''[{"name":"3","value":"false","childNodes":[{"name":"4","value":"false"}]}]''' == processData(testString)
    }
}

相关问题