如何从Google Apps脚本项目属性中存储和检索对象?

Dou*_*ell 5 javascript google-apps-script

我想在google apps脚本属性中存储对象.

让我们说我有一个对象: var myObject = {var1:"stuffval", var2:"stuff2val"};

如果我通过scriptProperties.setProperty("myProperty", myObject );属性将其存储为属性,则存储为字符串{var1=stuffval, var2=stuff2val}.

如何在Google Apps脚本中从该字符串中检索我的对象?

Ala*_*lls 9

在将对象放入Properties Service之前将其转换为字符串.所有Properties Services都将数据存储为字符串.属性服务将在存储数据之前自动将非字符串转换为字符串,但是对于对象,您应该使用该JSON服务将对象正确地转换为字符串.然后将对象作为字符串转换回真实对象JSON.parse(theObject)

var myObject = {var1:"stuffval", var2:"stuff2val"};//Example - object literal

PropertiesService.getScriptProperties()
  .setProperty("myProperty", JSON.stringify(myObject) );//stringify the object
Run Code Online (Sandbox Code Playgroud)

转换回对象:

var returnedObj = PropertiesService.getScriptProperties("myProperty");
returnedObj = JSON.parse(returnedObj);
Run Code Online (Sandbox Code Playgroud)

不要使用scriptProperties它已被弃用.