Dears,
Apart from the simplest way of using variables in output texts, i.e. ${variable}, and apart from more advanced way of giving dynamic variations, i.e. singular or plural, like ${nSomethingCounted>1?nSomethingCounted + “many”:“one”}, what other possibilities we have to use code lines in outputs?
For example, I’d like to use the following line in an output
jsonAnswer.each {println it};
which returns on separate lines data from a list in jsonAnswer variable.
For more clarity I am giving below the code I use, including some json mockup data at the beginning.
Once parsed, the data is a List of Lists, and I am extracting certain keys, where [“amount”] is more than zero. Then display each from this filtered list.
But I am not able to assign it to a variable and use it in output text, as once done it becomes a list again (and square brackets appear [ ] ).
Here is a screen shot from a groovy web console what is the result I am getting (and I want to get ), the question is how to present the same result in an output text (and possibly format “amount” as decimal).
After the screen shot, is the code that produces the result in the groovy console.
I’d highly appreciate your help
def testJson = ‘’’[ {
“amount”: 10,
“measure_unit”: “VOL”,
“unit”: 5108.11,
“description”: “Megabytes”,
“category”: “DISCS”
},
{
“amount”: 0,
“measure_unit”: “QUANTITY”,
“unit”: 2,
“description”: “Messages”,
“category”: “OTHERS”
},
{
“amount”: 3.33,
“measure_unit”: “QUANTITY”,
“unit”: 3,
“description”: “Games and fun”,
“category”: “CONTENT/OTHERS”
},
{
“amount”: 0,
“measure_unit”: “DUR”,
“unit”: 0.3,
“description”: “Talks”,
“category”: “WALK”
}
]’’’;
def json = new groovy.json.JsonSlurper().parseText(testJson);
//println "parsed JSON: "+ json;
def json2 = [];
json2 = json.findAll() { it.amount > 0 };
def jsonAnswer = [];
jsonAnswer = json2.collect {"$it.description - $it.amount;"};
jsonAnswer.each {println it}; // → this is the line I want to use in the output text…