如何在groovy中查找变量的数据类型

时间:2017-12-12 10:55:23

标签: json groovy

下面是我的groovy代码,其中我使用json数据构建命令,但json数据具有不同类型的数据,如数组中的列表,或者只有单个变量,所以任何人都可以告诉我如何查找变量的数据类型。

下面的代码我突出了一个元素“jsondata [key]”,这是我的键值,我想检查这些值的数据类型,就像在我的JSON数据中我有params(键)4数组列表(值)所以在使用params值之前我已检查数据类型。

我的预期结果:

key : [1 2 3]

if (typeof(key) == list) {
    for (value in key) {
        #here i want to frame a command using previous keys..
    } 
}
  

类似于python中的typeof()

import groovy.json.JsonSlurper

def label = "test testname params"

File jsonFile = newFile("/home/developer/Desktop/kramdeni/vars/PARAMS.json")
def jsondata = new JsonSlurper().parse(jsonFile)
println jsondata.keySet()
println "jsondata: " + jsondata

def command = ""
keys = label.split(" ")
println "keys: " + keys

for (key in keys) {
    command += "-" + key + " " + **jsondata[key]** + " "
}
println "command: " + command

我的json数据:

{
    "test": "iTEST",
    "testname": "BOV-VDSL-link-Rateprofile-CLI-Test-1",
    "params": [
        {
            "n2x_variables/config_file": "C:/Program Files (x86)/Agilent/N2X/RouterTester900/UserData/config/7.30 EA SP1 Release/OSP  Regression/BOV/Bov-data-1-single-rate-profile.xml"
        },
        {
            "n2x_variables/port_list": "303/4 303/1"
        },
        {
            "n2x_variables/port_list": "302/3 303/4"
        },
        {
            "n2x_variables/port_list": "301/3 303/5"
        }
    ]
}

2 个答案:

答案 0 :(得分:3)

jsondata.each{ entry->
   println entry.value.getClass()
}

答案 1 :(得分:1)

以下代码说明了instanceofString类型的List

import groovy.json.JsonSlurper

def label = "test testname params"
def jsonFile = new File("PARAMS.json")
def jsondata = new JsonSlurper().parse(jsonFile)
def command = ""
def keys = label.split(" ")

for (key in keys) {
    def value = jsondata[key]

    if (value instanceof String) {
        println "${key} ${value}"
    } else if (value instanceof List) {
        value.each { item ->
            println "${key} contains ${item}"
        }
    } else {
        println "WARN: unknown data type"
    }
}

指定JSON的示例输出(我不确定如何构建command,因此这是简单的输出。应该很容易根据需要构建command) :

$ groovy Example.groovy 
test iTEST
testname BOV-VDSL-link-Rateprofile-CLI-Test-1
params contains [n2x_variables/config_file:C:/Program Files (x86)/Agilent/N2X/RouterTester900/UserData/config/7.30 EA SP1 Release/OSP  Regression/BOV/Bov-data-1-single-rate-profile.xml]
params contains [n2x_variables/port_list:303/4 303/1]
params contains [n2x_variables/port_list:302/3 303/4]
params contains [n2x_variables/port_list:301/3 303/5]