{
"Product": [{
"flm": [{
"101": [{
"value": "R36.0 flm",
"revision": ["111","11br"]
}]
"101.1": [{
"value": "R36.0 flm",
"revision": ["111","11br","11we"]
}]
"202": [{
"value": "R37.0 flm",
"revision": ["111"]
}]
"301": [{
"value": "R38.0 flm",
"revision": ["222"]
}]
}]
"cod": [{
"101": [{
"value": "R36.0 cod",
"revision": ["111"]
}]
"202": [{
"value": "R37.0 cod",
"revision": ["111"]
}]
"301": [{
"value": "R38.0 cod",
"revision": ["222"]
}]
}]
"lsp": [{
"101": [{
"value": "R36.0 lsp",
"revision": ["111","11br"]
}]
"202": [{
"value": "R37.0 lsp",
"revision": ["111"]
}]
"301": [{
"value": "R38.0 lsp",
"revision": ["222"]
}]
}]
"urm": [{
"101": [{
"value": "R36.0 urm",
"revision": ["111","11br"]
}]
"202": [{
"value": "R37.0 urm",
"revision": ["111"]
}]
"301": [{
"value": "R38.0 urm",
"revision": ["222"]
}]
}]
}]
}
我想使用groovy打印/访问json文件中的值/修订字段,如果产品是(lsp和101),则比较它是否与我的输入匹配(“11br”,R36.0 lsp)。我只能到达101,后来我不知道如何提取更多的值。任何帮助表示赞赏
答案 0 :(得分:1)
您可以使用JsonSlurper.parseText(json)
- 它将生成一个地图地图,您可以遍历并提取有趣的值。在你的情况下,重要的是要提到你必须处理对象列表(通常它们只包含一个对象),因此遍历将产生列表列表等。在这种情况下,Groovy的.flatten()
方法是很有帮助。请考虑以下脚本:
import groovy.json.JsonSlurper
def json = '''
{
"Product": [
{
"flm": [
{
"101": [
{
"value": "R36.0 flm",
"revision": [
"111",
"11br"
]
}
],
"101.1": [
{
"value": "R36.0 flm",
"revision": [
"111",
"11br",
"11we"
]
}
],
"202": [
{
"value": "R37.0 flm",
"revision": [
"111"
]
}
],
"301": [
{
"value": "R38.0 flm",
"revision": [
"222"
]
}
]
}
],
"cod": [
{
"101": [
{
"value": "R36.0 cod",
"revision": [
"111"
]
}
],
"202": [
{
"value": "R37.0 cod",
"revision": [
"111"
]
}
],
"301": [
{
"value": "R38.0 cod",
"revision": [
"222"
]
}
]
}
],
"lsp": [
{
"101": [
{
"value": "R36.0 lsp",
"revision": [
"111",
"11br"
]
}
],
"202": [
{
"value": "R37.0 lsp",
"revision": [
"111"
]
}
],
"301": [
{
"value": "R38.0 lsp",
"revision": [
"222"
]
}
]
}
],
"urm": [
{
"101": [
{
"value": "R36.0 urm",
"revision": [
"111",
"11br"
]
}
],
"202": [
{
"value": "R37.0 urm",
"revision": [
"111"
]
}
],
"301": [
{
"value": "R38.0 urm",
"revision": [
"222"
]
}
]
}
]
}
]
}
'''
def root = new JsonSlurper().parseText(json)
def lsp101 = root.Product.lsp.'101'.flatten()
def value = lsp101.value.first()
def revisions = lsp101.revision.flatten()
def expectedValue = 'R36.0 lsp'
def expectedRevision = '11br'
assert expectedValue == value && expectedRevision in revisions
它为路径value
提取revisions
和$.Product.lsp.101
列表,并与预期值进行比较。希望它有助于理解如何在Groovy中使用JSON。有关更多信息和示例,请不要犹豫,访问详细介绍如何使用JSON的Groovy手册页 - http://groovy-lang.org/json.html