且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Zapier-抓钩-JSON数组-遍历数组中的每个项目

更新时间:2023-11-28 15:48:46

因此,第一部分是Catch Raw Hook的触发器.这是正常的"Webhooks",但是您必须单击以显示较不常见的变体.使用 Catch Raw Hook ,您的数据将不会通过Zapier应用自动转换为变量,而您将获得原始JSON数据.

So, the first part is to Catch Raw Hook for a trigger. It's the normal "Webhooks", but you have to click to show the less common variations. With the Catch Raw Hook, your data will not be turned automatically turned into variables via the Zapier app, you'll have the raw JSON data.

一旦有了原始的JSON,就我而言,您将有一个动作,这就是代码"动作.我正在使用JavaScript.在我的模板中,我正在获取整个JSON字符串(您现在导入的整个JSON是一个字符串,而不是一个对象,因此我们不能使用"."(点)表示法来访问部件的).

Once you have the raw JSON, in my case, you'll have an action, and this will be the "Code" action. I'm using JavaScript. In my template, I'm grabbing the entire JSON string (your whole imported JSON is a string right now, not an object, so we can't use "." (dot) notation to access parts of it).

您需要JSON.parse()代码中的字符串.但是首先,让我解释一下Zapier有一个预定义的变量,称为inputData,您将在代码中使用它.然后,在代码" Action 的编辑模板"部分的顶部,您将看到可以命名导入的JSON字符串的变量.

You'll need to JSON.parse() the string in the code. But first, let me explain that Zapier has a pre-defined variable called inputData that you'll use in your code. Then in the top of the "Edit Template" section of your "Code" Action, you'll see you can name the variable of that JSON string you imported.

现在有趣的部分!在代码中,您将输入:

Now the fun part! In the code, you'll type:

// of course, you can change the variables to what you want
// but 'inputData' is unique, can't change that
const myData = JSON.parse(inputData.rawJsonData); 

因此,我的原始数据是一个字符串,它还不是JSON,因此此代码行使其成为JSON对象.现在,作为对象,我们可以在它或.map上循环或访问"this.that"或您想要的任何对象.

So, my raw data is a string, it's not JSON yet, so this line of code makes it a JSON object. And now, as an object we can loop over it or .map or access 'this.that' or whatever you want.

关于Zapier中代码"的下一件重要的事情是,return.因此,在接下来的几行中,我将返回一个.map函数,该函数返回数组中的每个项目.很难掌握Zapier的处理方式,但是每次在该.map中循环时,它实际上都会运行您创建的下一个动作"(例如,在工作表中添加一行).因此,让我们在下面看一下:

The next important thing to mention about "Code" in Zapier, is that to get your stuff out, you return. So, in the next few lines, I'm going to return a .map function that returns each item in an array. And it's tough to grasp how Zapier treats this, but it actually runs the next "Action" you create (e.g. adding a row to a sheet) for each time you loop in that .map. So, let's take a look below:

return myData.data.map(item => {
    return item;
});

如果您还记得的话,我在原始问题中列出的原始JSON中有一个名为"data"的数组.它将遍历该数组,并且由于要执行return操作,因此它将为每个循环执行将行添加到工作表"(以我为例),从而将我的所有数据作为多行插入到电子表格中.

If you remember, I had an array called "data" in my raw JSON I listed in the original question. It will loop over that array and since I'm returning, then it will perform an "Add Row to Sheet" (in my case) for each loop, thus, inserting all of my data as multiple rows in my spreadsheet.

因此,完成的代码:

const myData = JSON.parse(inputData.rawJsonData);

return myData.data.map(item => {
    return item; 
});