Issue
I am trying to get a list of values from the Json output.
MY CODE :
def VALUES_BEFORE = sh """
curl -X POST "http://node-01.xyz.com:32010/abc/def" \\
-H "accept: application/json" \\
-H "Content-Type: application/json" \\
-d '{ "cell_ids": [${payload}] }' | json_pp
"""
def json = readJSON text: VALUES_BEFORE
def mylist = json .value
echo "Values are ${mylist}"
Output is below JSON :
[
{
"def" : "bins",
"value" : 294
},
{
"def" : "valid_bins",
"value" : 294
},
{
"def" : "covered_bins",
"value" : 1
},
{
"def" : "sum",
"value" : 415
},
{
"def" : "histro",
"value" : "-130.0 -> -120.0: 129 | -120.0 -> -110.0: 82 | -110.0 -> -100.0: 20 | -100.0 -> -90.0: 1 | -90.0 -> -80.0: 0 | -80.0 -> -70.0: 0 | -70.0 -> -60.0: 0 | -60.0 -> -50.0: 0"
}
]
Expected result :
"value" : "-130.0 -> -120.0: 129 | -120.0 -> -110.0: 82 | -110.0 -> -100.0: 20 | -100.0 -> -90.0: 1 | -90.0 -> -80.0: 0 | -80.0 -> -70.0: 0 | -70.0 -> -60.0: 0 | -60.0 -> -50.0: 0"
Your help would be helpful. Thanks
Solution
Essentially a straight-forward one-liner, using findResult
:
import groovy.json.*
def json = new JsonSlurper().parseText '''\
[
{
"def" : "bins",
"value" : 294
},
{
"def" : "valid_bins",
"value" : 294
},
{
"def" : "covered_bins",
"value" : 1
},
{
"def" : "sum",
"value" : 415
},
{
"def" : "histro",
"value" : "-130.0 -> -120.0: 129 | -120.0 -> -110.0: 82 | -110.0 -> -100.0: 20 | -100.0 -> -90.0: 1 | -90.0 -> -80.0: 0 | -80.0 -> -70.0: 0 | -70.0 -> -60.0: 0 | -60.0 -> -50.0: 0"
}
]'''
String result = json.findResult{ 'histro' == it.def ? it.value : null }
assert result == '-130.0 -> -120.0: 129 | -120.0 -> -110.0: 82 | -110.0 -> -100.0: 20 | -100.0 -> -90.0: 1 | -90.0 -> -80.0: 0 | -80.0 -> -70.0: 0 | -70.0 -> -60.0: 0 | -60.0 -> -50.0: 0'
Answered By - injecteer Answer Checked By - Dawn Plyler (WPSolving Volunteer)