0

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

2 Answers 2

1

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'
Sign up to request clarification or add additional context in comments.

1 Comment

showoff 😜 hee hee
1

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"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.