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

谁都会走 提交于 2019-12-03 08:01:35

Yes, you can use a simple script, Javascript or Python. Click the + in between your existing Trigger and Action, and add an Action, choosing Code by Zapier as the app. Assuming your JSON is the output of your Trigger:

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

Code by Zapier would present you with these options:

Setup Code by Zapier Run Javascript

If the array of objects data has more than one element, then Zapier presents all values for the property type in those objects as an array labelled Data Type and all values for property id as an array labelled Data ID. If you choose type and id as the property names for the input object to be passed to the Code app, then the Javascript object your code gets is this:

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

Your code can then transform the data any way you want, before passing to the next Action.

Code by Zapier,

Brian Schuster

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

If you're talking about parsing it uses Zapier's Code By Zapier JavaScript engine, then here's what you do:

Zapier returns whatever object you tell it to, so assuming you use their standard name for input, here's what you do:

output = {};

for (var i = 0; i < input["data"].length; i++) {
  output["myObject"+str(i)] = input.data[i];
}

This should return an object called output that looks as follows:

"output" : {
    "myObject0" : {  
      "type": "name",
      "id": "123"
    },
    "myObject1" : {
      "type" : "name",
      "id": "124"
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!