嵌套JSON结构的解析

huwehgph  于 2022-10-07  发布在  其他
关注(0)|答案(2)|浏览(254)

我试图通过使用groovy从下面的嵌套Json结构中使用“ColumnName”字段来获取“Value”。因为“Cells”列下面的数字是动态的,所以Find选项非常有效。在下面的示例“Camp”中,有没有一种方法可以根据“ColumnName”=“Type”获得值?

{
"type": "CATEGORY"
"cells": {
        "1309939": {
            "value": 120000,
            "columnName": "Planned spend"
        },
     "1309940": {
            "value": 12000,
            "columnName": "current spend"
        },
     "1309948": {
            "value": "CAMP",
            "columnName": "Type"
        }
}

任何建议都会很有帮助。

ulydmbyx

ulydmbyx1#

带有findResult的一行代码:

import groovy.json.*

def json = new JsonSlurper().parseText '{ "type": "CATEGORY", "cells": {         "1309939": {             "value": 120000,             "columnName": "Planned spend"         },      "1309940": {             "value": 12000,             "columnName": "current spend"         },      "1309948": {             "value": "CAMP",             "columnName": "Type"         } }'

def res = json.cells.findResult{ k, v -> 'Type' == v.columnName ? v.value : null }

assert res == 'CAMP'
xa9qqrwz

xa9qqrwz2#

您可以遍历所有的“Cells”,找到具有预期的ColumnName的单元格,然后如下所示获取值:

def json = '''{
"type": "CATEGORY",
"cells": {
        "1309939": {
            "value": 120000,
            "columnName": "Planned spend"
        },
     "1309940": {
            "value": 12000,
            "columnName": "current spend"
        },
     "1309948": {
            "value": "CAMP",
            "columnName": "Type"
        }
}'''

import groovy.json.*

def parsed = new JsonSlurper().parseText(json)

def result = parsed.cells*.value.find { element ->
    element.columnName == "Type"
}.value

assert result == "CAMP"

相关问题