来自 Salesforce 的对象在 Google 应用 Script/Javascript 中被解释为字符串

Object from Salesforce is interpreted as a String in Google Apps Script/Javascript

我们将数据从 Salesforce 提取到 Google 文档中,Google Apps 脚本正在从 Salesforce 获取 HTTP 请求。我们有一个来自 salesforce 的名为 "products" 的对象,但 Google Apps 脚本将其解释为字符串。

function doGet(product)

var productVar = product;

Logger.log(productVar);

结果是这样的:

"(OpportunityProduct1:{Product10Id=01726388aaa, Quantity=4.00, ListPrice=3.0, Sales_Price__A=3.00})"

我们能否将其作为对象获取,或以任何方式将其转换为 object/list/array。

首先使用 JavaScript 字符串方法编辑字符串。

function processString() {

  var originalStr = "(OpportunityProduct1:{Product10Id=01726388aaa, Quantity=4.00, ListPrice=3.00, Sales_Price__A=3.00})";
  var i=0, thisCharacter = "";
  //Remove spaces
  for (i=0;i<originalStr.length;i+=1) {
    thisCharacter = originalStr[i];
    //Logger.log(thisCharacter)
    if (thisCharacter === " ") {
      Logger.log(i);
      var front = originalStr.slice(0,i);
      var back = originalStr.slice(i+1);
      originalStr = front + back;
    };
  };

  Logger.log(originalStr)
  var strNewObject = "";

  var myRegEx = new RegExp("=","g");

  strNewObject = originalStr.replace(myRegEx, '":"');

  strNewObject = strNewObject.replace("{", '{"');
  strNewObject = strNewObject.replace("}", '"}');
  strNewObject = strNewObject.replace(/,/g, '","');

  strNewObject = strNewObject.replace("(", '{"'); //Need out curly brace for valid JSON
  strNewObject = strNewObject.replace(")", "}"); //Need out curly brace for valid JSON
  strNewObject = strNewObject.replace(":", '":'); //

  Logger.log('strNewObject: ' + strNewObject);

  var newObject = JSON.parse(strNewObject);

  Logger.log(newObject);
  Logger.log(typeof newObject);


  Logger.log(newObject.OpportunityProduct1.Quantity)
};

您可以使用 JSON 服务将字符串转换回对象:

var myNewObject = JSON.parse(productVar);

在 Apps 脚本编辑器中使用快捷键 "Ctrl" + "Space bar" 调出可用服务列表。

如果您相信它不包含恶意代码,您可以 var productObject = eval(productVar);