How do I JSON.parse an array in a Zapier Trigger?

Wesley Davis picture Wesley Davis · Apr 3, 2016 · Viewed 11.8k times · Source

I am trying to JSON.parse the array "data." I need to be able to pass the array as the root.

{
  "data": [
    {
      "type": "name",
      "id": "123"
    }
  ]
}

The response should look like this containing only objects. Zapier doesn't seem to work well with arrays.

{
      "type": "name",
      "id": "123"
}

Shouldn't I be able to use a simple script to get the job done?


EDIT:

Essentially, you're going to want to override the post_poll method (https://zapier.com/developer/documentation/v2/scripting/#polling) in scripting so you can intercept the response of the API. After that, you just need to return a new object with the values you want. Instead of returning: {"data":[ {...}, {...}, ]}, you just need to return the value of data. Something like:

xyz_post_poll: function(bundle){
  var response = JSON.parse(bundle.response.content);
  return response.data || [];
}

Answer

Brian Schuster picture Brian Schuster · Mar 6, 2018

I found that I needed to call JSON.parse() and JSON.stringify() in order to get this to work. Assume that my input gets putted in Zapier as (key,value) where the key = data and the value is:

[{"type": "name", "id":"123"}, {"type": "name2", "id":"456"}, 
  {"type": "name3", "id":"789" }]

My code:

output = {};

var obj = JSON.parse(input.data);

for (var i = 0; i < obj.length; i++) {
   output["myObject"+i] = JSON.stringify(obj[i]);
}

The output generated is:

myObject0: {"type":"name", "id":"123"}
myObject1: {"type":"name2", "id":"456"}
myObject2: {"type":"name3", "id":"789"}