Best answer

Return JSON Array from Code step

  • 21 June 2021
  • 3 replies
  • 783 views

Userlevel 1

Hi there,

I am quite new to this and trying to achieve a specific function to make something a little more automatic.

I have a Search Action configured and am trying to return to objects in the resources array in the response.

 

Raw response from API

{

    "meta": {

        "query_time": 1.92e-7,

        "pagination": {

            "offset": 1,

            "limit": 100,

            "total": 1

        },

        "trace_id": "9af6da38-4f8a-45ad-bab8-f4277c4395b1"

    },

    "resources": [

        "943ab1234"

    ],

    "errors": []

}

 

What I have in the Zapier API Endpoint

 const options = {
  url: 'https://api.example.com/devices/queries/host-group-members',
  method: 'GET',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'authorization': `bearer ${bundle.authData.access_token}`
  },
  params: {
    'id': '123456'
  }
}

return z.request(options)
  .then((response) => {
    response.throwForStatus();
    const results = z.JSON.parse(response.content);
    // You can do any parsing you need for results here before returning them

    return results.resources;
  });

 

What I get as a response when testing the above Zapier API Request

{
  "0": "9",
  "1": "4",
  "2": "3",
  "3": "a",
  "4": "b",
  "5": "1",
  "6": "b",
  "7": "1",
  "8": "2",
  "9": "3",
  "10": "4",
}

 

I feel like I am close, I just can’t work out how to get the response as one item rather than each digit Breaking out into a new object…

 

Appreciate any guidance you’ll have.

icon

Best answer by GetUWired 22 June 2021, 14:55

View original

This post has been closed for comments. Please create a new post if you need help or have a question about this topic.

3 replies

Userlevel 7
Badge +14

Hi @daryl_HBL 

Looks as though you are using a Code step in the Zap to perform the API request.

Try instead to use the Webhooks action step to do the API request.

https://zapier.com/apps/webhook/integrations#triggers-and-actions

 

Userlevel 7
Badge +12

Hi @daryl_HBL 

Zapier is expecting that you will return an array of objects. Since resources is an array of strings, Zapier is likely doing some type casting to turn it into an object. Your code will need to loop through the array and translate the string values to objects. it could be something as simple as a forEach loop

let output = [];
results.resources.forEach(string => {
output.push({resource: string})
})

return output



 

Userlevel 1

Thank you @GetUWired , that did infact do exactly what I needed.