Say I have json response that looks like this and I just want to check if "stable" or "beta" is in the response how would I do that?
{
"stable": {
"version": "0.5.0",
"build_id": "20210610-122506"
}
"beta": {
"version": "0.5.1",
"build_id": "20210610-122509"
}
Cobra
November 26, 2021, 9:19am
2
I think the quickest way is to use 'contains()'
if you put the response into a variable called 'response' as a string then...
if(response.contains("stable")){
do something
}
else{
do something else
}
Andy
hmm not working
groovy.lang.MissingMethodException: No signature of method: groovy.json.internal.LazyMap.contains() is applicable for argument types: (java.lang.String) values: [stable]
Cobra
November 26, 2021, 9:37am
4
Did you convert the response to string?
I'm pretty sure I have used this before
How do i convert it to a string? gosh its been so long since i code groovy i went stupid
Cobra
November 26, 2021, 9:41am
6
response=response.toString()
I know the feeling.. I have been using java in Node-red for so long I had to think about it
NR uses 'includes()'
1 Like
You should be able to use one of the find calls shouldn't you, if it is translated to a map?
Cobra
November 26, 2021, 9:45am
8
Probably, but it's been a while and my answer was the 1st thing I thought of
It should work if the response is converted to a string
1 Like
sburke781:
find calls
explain.. is that faster?
Let me look over some of my code...
Cobra
November 26, 2021, 9:50am
13
something like...
answer = response.get("stable")
But that might only work with key/value pairs
1 Like
So I would still need to convert it to a string like this first?
response = "${obs.toString()}"
Yep, that's it:
boolean findAlbum(String partist, String palbum) {
boolean result = false;
def albumDetail = [:];
if(state.albumList != null) {
albumDetail = state.albumList.get(partist)?.get(palbum);
}
debugLog("findAlbum: Artist = ${partist}, Album = ${palbum}, Album Detail = ${albumDetail}")
if (albumDetail != null) { result = true }
return result
}
1 Like
So that's a bit more code than what I am using now
obs = resp.data
response = "${obs.toString()}"
if(response.contains("stable")) {
sendEvent(name: "StableUpdate", value: "<font color='green'>FW_Update_Available</font>", isStateChange: true);
}
else if(response.contains("beta")) {
sendEvent(name: "BetaUpdate", value: "<font color='red'>BETA_FW_Available</font>", isStateChange: true);
}
Cobra
November 26, 2021, 9:54am
17
If it's a map then you would not convert to a string to use the 'get' command
But as I said I think this only works with key/value pairs
The original way is how I would do it as I know this works
2 Likes
The only concern would be if the word is contained in any other part of the string
There is also the ? notation, forget what it's called now... Null Safe was what I was thinking of.... bit late now...