Groovy slurper 解析变量的变量

huangapple go评论49阅读模式
英文:

Groovy slurper.parser variable of a variable

问题

这是我的Groovy脚本片段:

jsonFileData = slurper.parse(jsonFile)

这是我的JSON文件:

{
    "MEMXYZ": {
        "LINKOPT": {
            "RMODE": "31",
            "AMODE": "ANY"
        },
        "PROCESSOR": "PROCESSOR XYZ",
        "DB2": {
            "OWNER": "USER1",
            "QUALIFER": "DB2ADMIN",
            "SSID": "DBC1"
        },
        "COBOL": {
            "VERSION": "V6",
            "CICS": "V5R6M0",
            "OPTIONS": "LIST,MAP,RENT",
            "DB2": "YES"
        }
    }
}
println "Print1 ***** Parsing PROCESSOR  = ${jsonFileData.MEMXYZ.PROCESSOR}"
println "Print2 ***** Parsing PROCESSOR  = ${jsonFileData.${Member}.PROCESSOR}"

Print1 使用明确的Member名称 "MEMXYZ" 可以正常工作,但我在Print2中遇到问题,我需要进行动态的 ${Member} 变量替换。请帮忙!

${Member} 是 MEMXYZ

请帮忙解决Print2语句。

英文:

Here is the snippet of my groovy script:
jsonFileData = slurper.parse(jsonFile)

Here is my JSON file

{
    "MEMXYZ": {
        "LINKOPT": {
            "RMODE": "31",
            "AMODE": "ANY"
        },
        "PROCESSOR": "PROCESSOR XYZ",
        "DB2": {
            "OWNER": "USER1",
            "QUALIFER": "DB2ADMIN",
            "SSID": "DBC1"
        },
        "COBOL": {
            "VERSION": "V6",
            "CICS": "V5R6M0",
            "OPTIONS": "LIST,MAP,RENT",
            "DB2": "YES"
        }
    }
}
println "Print1 ***** Parsing PROCESSOR  = ${jsonFileData.MEMXYZ.PROCESSOR}"
println "Print2 ***** Parsing PROCESSOR  = ${jsonFileData}.${Member}.PROCESSOR"

The Print1 is working fine with with explicit Member name "MEMXYZ", but I have problem with Print2, which I need to have the dyanmic ${Member} variable substitution. Please help!

${Member} is MEMXYZ

Please help to solve the Print2 statement

答案1

得分: 0

`".. ${abc} ..."` 只是将 `abc` 变量的值注入到字符串中。

要访问地图的值(在您的情况下是 `slurper.parse(...)` 的结果),您可以使用以下一种方法:

jsonFileData[Member].PROCESSOR
jsonFileData[Member]['PROCESSOR']


因此,您的打印行可能如下所示:

println "PROCESSOR = ${jsonFileData[Member].PROCESSOR}"

英文:

".. ${abc} ..." just injects the value of abc variable into string.

To access values of map (result of slurper.parse(...) in your case) you could use one of approaches:

jsonFileData[Member].PROCESSOR
jsonFileData[Member]['PROCESSOR']

So, your print line could look like:

println "PROCESSOR  = ${jsonFileData[Member].PROCESSOR}"

huangapple
  • 本文由 发表于 2023年2月18日 01:55:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/75487735.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定