Handle a webhook that is sometimes has a body with multiple objects

I’m getting notifications to my webhook that are sometimes slightly different and not sure how to handle these.

Sometimes the body has a single object

  {
    "headers": {
      "xyz": "123",
      
    },
    "body": [
      {
        "eventId": 2487886085,
        "objectId": 135301
      }
    ]
  }
]

If I use the interface to select the objectId to use in the node after my webhook, it’s set as {{ $json.body[0].objectId }} which works fine when there is only one object in the body. But sometimes I get something like:

[
  {
    "headers": {
      "xyz": "123",
      
    },
    "body": [
      {
        "eventId": 2487886086,
        "objectId": 135302
      },
      {
        "eventId": 2487886087,
        "objectId": 135303
      },
      {
        "eventId": 24878860878,
        "objectId": 135304
      }
    ]
  }
]

Obviously {{ $json.body[0].objectId }} then only gets the first object and the rest are thrown out. Is there a way to ensure these get looped like {{ $json.body[i].objectId }}? where i is some index that the node understands?

I’ve tried getting my webhook source to only send one object at a time, but Hubspot will often batch notifications if it feels like and there’s no way to prevent it.

Thanks,
JMR

Hi @jmr123, I’d use the Item Lists node here to split out your body field. This will work regardless of whether your array has a single item or 100 items:

Example workflow:

After the Item Lists node you can simply use expressions like {{ $json.objectId }} as most n8n nodes will run for each individual item they receive.

Hope this helps!

2 Likes

Thanks! I had no idea this was a thing…I wrote custom code for no reason apparently!

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.