Problem with script in transform accessing an array

Hi, I want to return the length of an array in a transform script within the logging action. I am doing this:

  "actions": {
    "log": {
      "transform": {
        "script": "return [total_snapshots : ctx.payload.snapshots.length]"
      },
      "logging": {
        "text": "Found {{ctx.payload.total_snapshots}} snapshots at {{ctx.execution_time}}"
      }
    }
  }

I can get back an array of objects using ct..payloaad.snapshots.snapshot but I want to have the length of the array. Does someone know whether this is possible and how?

Thanks.

I found the way to make this work, can't stop thinking I must have tried this before. Still it does work now with the following code:

  "actions": {
    "log": {
      "transform": {
        "script": "return [total_snapshots : ctx.payload.snapshots.size()]"
      },
      "logging": {
        "text": "Found {{ctx.payload.total_snapshots}} snapshots at {{ctx.execution_time}}"
      }
    }
  }

Hi Jettro,

I'm glad you figured it out! Thanks for sharing the working solution :smile:

Jettro, looks like snapshots is not an array, but a list? Is it by any chance coming from a json payload? for real "arrays" .length should indeed work (as well as size())

The payload is coming from this response, it looks line an array to me in Json. Not sure what groovy does with it though. From the jsonslurper documentation I read they convert arrays to lists. In that case what you're saying @url sounds like the reason. It is a List not and array.

{
   "snapshots": [
      {
         "snapshot": "conferences-20150619094018", //removed other fields
      },
      {
         "snapshot": "conferences-20150619113941",
      },
      {
         "snapshot": "conferences-20150621223930",
      },
      {
         "snapshot": "conferences-20150621224116",
      }
   ]
}

so if it's coming from json, then actually its watcher that converts the json arrays to lists :)... I just wasn't sure where you're gettings snapshots from (it could have been from a script transform)