Twilio Studio-使用Liquid选择和解析JSON

问题描述

在Twilio Studio中,我正在发出GET请求,并试图解析JSON,然后基于解析的JSON分配变量。我很难用返回的JSON进行操作。

基本上,我正在尝试设置与返回的JSON匹配的“行”中的变量(用户拨入,输入其PIN {{widgets.PIN_Entry.Digits}},该PIN将与从GET请求返回JSON,我们为匹配的行设置了userID,userEmail,userName,userPin变量。

{
  "DataSource": {
    "Id": "12345","Name": "Dial-In Subscribers","Rows": [
      [
        "EMP-0226","[email protected]","Ron Swanson","00054321"
      ],[
        "EMP-0267","[email protected]","Leslie K@R_404_6457@e","00012345"
      ]
    ],"TotalRows": 2,"LastUpdated": "2020-08-26T03:39:42.7670000Z","CompanyId": 12345
  }
}

我可以轻松地使用JSON Path(Twilio工作室不支持)来执行此操作,以选择要设置为变量的值,但是我不知道如何使用Liquid来执行此操作。

userID == $ .DataSource.Rows [?(@。includes('00012345'))] .. [0]

(将返回“ EMP-0267”)

userEmail == $ .DataSource.Rows [?(@。includes('00012345'))] .. [1]

(将返回“ [email protected]”)

userName == $ .DataSource.Rows [?(@。includes('00012345'))] .. [2]

(将返回“莱斯利·诺普”)

userPin == $ .DataSource.Rows [?(@。includes('00012345'))] .. [3]

(将返回“ 00012345”)

有人可以分享一些关于如何使用Liquid解析JSON和设置变量的想法吗?这就是我想实现的方式:

  1. 将变量{{widgets.PIN_Entry.Digits}}匹配到返回的JSON中的一行
  2. 解析所选行并为userID,userEmail,userName,userPin设置变量。

解决方法

在这种情况下,我使用Run Function Widget,我发现处理液体语法的细微之处要容易得多。

// Description
// Make a read request to an external API

// Add axios 0.20.0 as a dependency under Functions Settings,Dependencies
const axios = require('axios');

exports.handler = function (context,event,callback) {
  
  let twiml = new Twilio.twiml.VoiceResponse();
  
  // Arrays start at 0
  let selectedDigit = 0;

  axios
    .get(`https://x.x.x.x/myAPI`)
    .then((response) => {
      
      let { Rows } = response.data.DataSource;

      let result = Rows.filter((record,index) => index === selectedDigit);
      
      twiml.say(`The result is ${result}`);
      
      return callback(null,twiml);
    })
    .catch((error) => {
      console.log(error);
      return callback(error);
    });
};