I am trying to get the "value" using the field "ColumnName" from the below nested Json structure using groovy. Since the numbers below the "Cells" column will be dynamic, the find option is very effective. Is there a way to get the value, in the below example "CAMP" based on the "columnName" = "Type"
{
"type": "CATEGORY"
"cells": {
"1309939": {
"value": 120000,
"columnName": "Planned spend"
},
"1309940": {
"value": 12000,
"columnName": "current spend"
},
"1309948": {
"value": "CAMP",
"columnName": "Type"
}
}
Any suggestions will be very helpful
CodePudding user response:
One-liner with 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'
CodePudding user response:
You can go through all the "cells", find the one with the expected columnName, and then fetch the value like so:
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"