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

How can I store and retrieve objects from Google Apps Script Project Properties?

本文关键字:存储 检索 对象 属性 项目 Google Apps 脚本      更新时间:2023-09-26

我正在尝试将对象存储在谷歌应用程序脚本属性中。

假设我有一个对象:var myObject = {var1:"stuffval", var2:"stuff2val"};

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

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

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

var myObject = {var1:"stuffval", var2:"stuff2val"};//Example - object literal
PropertiesService.getScriptProperties()
  .setProperty("myProperty", JSON.stringify(myObject) );//stringify the object

转换回对象:

var returnedObj = PropertiesService.getScriptProperties("myProperty");
returnedObj = JSON.parse(returnedObj);

不要使用scriptProperties,它已被弃用。