Pattern matching

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"
   }

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]

Did you convert the response to string?

I'm pretty sure I have used this before :slight_smile:

How do i convert it to a string? gosh its been so long since i code groovy i went stupid

response=response.toString()

I know the feeling.. I have been using java in Node-red for so long I had to think about it :slight_smile:
NR uses 'includes()' :slight_smile:

1 Like

You should be able to use one of the find calls shouldn't you, if it is translated to a map?

Probably, but it's been a while and my answer was the 1st thing I thought of :slight_smile:

It should work if the response is converted to a string

1 Like

got it!!

Great!

1 Like

explain.. is that faster?

Let me look over some of my code...

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);
    }

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

gotcha

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...