Salesforce中的对象在Google Apps脚本/ Javascript中被解释为String

时间:2015-12-17 15:54:14

标签: javascript google-apps-script salesforce

我们将Salesforce中的数据提取到Google Doc,Google Apps脚本正在从Salesforce获取HTTP请求。我们有一个来自salesforce的“产品”对象,但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获取,或以任何方式将其转换为对象/列表/数组。

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

首先使用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);

使用快捷键&#34; Ctrl&#34; +&#34;空格键&#34;在Apps脚本编辑器中显示可用服务列表。