'Groovy: find a particular item from JSON array
JSON File
{
"FormElements": [
{
"ButtonLabel": [
"New",
"Done",
"Save as draft",
"Submit",
"Next",
"Finish"
],
"XPath": "//*[text()='LABEL']"
}
]
}
From the above JSON to find a particular item in the array. For example, I want to Find "New" from the above one. Below is my code but its return null
def isAvailable = InputJSON.FormElements.find {it."ButtonLabel[0]"=="New" }
Can anyone validate the above code, whether any changes are required in this?
Solution 1:[1]
Slight syntax error accessing ButtonLabel items. It should be,
def isAvailable = InputJSON.FormElements.find {it."ButtonLabel".[0]=="New" }
OR
def isAvailable = InputJSON.FormElements.find {it."ButtonLabel".get(0) == "New" }
Solution 2:[2]
Normally I would use indexOf.
InputJson.FormElements[0].ButtonLabel.indexOf('New')
-1 means its not present. Its hard to tell not knowing the source of your json... etc
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | aldrin |
| Solution 2 | SuperSpamTube |
