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
3
Answers
Since the JSON and/or Map was restructured into a list of maps with identical keys, there will be a need to iterate through the entire list and check the values of the key in each element’s map:
and for the example given in the question, the value of
myResult
will be:It would be easier and simpler if the data structure was a single-level map of key-value pairs with
def
value as the key andvalue
value as the value. It would be worth considering restructuring the response body accordingly if at all possible.Here some more simpler approaches of the previous answer:
Variant 1
Variant 2
This converts the json output to a map having
def
as the key andvalue
as the value. Then to access any entry use the map directly.Essentially a straight-forward one-liner, using
findResult
: