java jmeter -如何迭代json响应以获取所有键和相关值

k97glaaz  于 2023-03-16  发布在  Java
关注(0)|答案(1)|浏览(131)

有没有办法得到一个json的所有键和相关值?我不知道输出的字段,那我就不能用json提取器了。我找到了这段代码,但是它只返回键:

import groovy.json.JsonSlurper

def traverse
traverse = { tree, keys = [], prefix = '' ->
    switch (tree) {
        case Map:
            tree.each { k, v -> 
                def name = prefix ? "${prefix}.${k}" : k
                keys << name   
                traverse(v, keys, name)
            }
            return keys
        case Collection:
            tree.eachWithIndex { e, i -> traverse(e, keys, "${prefix}[$i]") }
            return keys
        default :
            return keys
    }
}

def content = new JsonSlurper().parseText(prev.getResponseDataAsString())

traverse(content).each { println it }

输出:

....
devices[24].creationDate
devices[24].updateDate
devices[24].attributes
devices[24].attributes.name
devices[24].attributes.location
devices[24].attributes.address
devices[24].attributes.latitude
devices[24].attributes.longitude
devices[24].attributes.brand
devices[25].deviceId
devices[25].deviceStatus
devices[25].deviceType
devices[25].creationDate
devices[25].updateDate
devices[25].attributes
....

你能帮我恢复键和值吗?
先谢了

m0rkklqb

m0rkklqb1#

现在还不太清楚JSON的样子以及期望什么形式的输出。
它可能是简单的:

content.keySet().each {println it}

或者,如果不是JSON Object,您可能希望修改代码以包含属性值,如下所示:

import groovy.json.JsonSlurper

def traverse
traverse = { tree, keys = [], prefix = '' ->
    switch (tree) {
        case Map:
            tree.each { k, v ->
                def name = prefix ? "${prefix}.${k}" : k
                if (!(v instanceof Map)) {
                    keys << ["$name": v]
                } else {
                    keys << name
                }
                traverse(v, keys, name)
            }
            return keys
        case Collection:
            tree.eachWithIndex { e, i -> traverse(e, keys, "${prefix}[$i]") }
            return keys
        default:
            return keys
    }
}

def content = new JsonSlurper().parseText(prev.getResponseDataAsString())

traverse(content).each { println it }

更多信息:

相关问题