如何从Google Apps脚本项目属性中存储和检索对象? [英] How can I store and retrieve objects from Google Apps Script Project Properties?
问题描述
我正在尝试将对象存储在Google Apps脚本属性中。
I am trying to store objects in google apps script properties.
假设我有一个对象: var myObject = {var1: stuffval,var2:stuff2val};
如果我通过 scriptProperties.setProperty将其存储为属性( myProperty,myObject);
该属性存储为 {var1 = stuffval,var2 = stuff2val}
的字符串。
If I store this as a property via scriptProperties.setProperty("myProperty", myObject );
the property is stored as a string that is {var1=stuffval, var2=stuff2val}
.
如何在Google Apps脚本中从该字符串中检索我的对象?
How can I retrieve my object from that string within Google Apps Script?
推荐答案
在将对象放入Properties Service之前将其转换为字符串。所有Properties Services都将数据存储为字符串。属性服务将在存储数据之前自动将非字符串转换为字符串,但是对于对象,您应该使用 JSON
服务将对象正确转换为字符串。然后使用 JSON.parse(theObject)将对象转换为实际对象
Convert the object to a string before putting it into Properties Service. All of the Properties Services store the data as a string. Properties Service will automatically convert non-strings to strings before storing the data, but with an object you should use the JSON
service to correctly convert the object to a string. Then convert the object as a string back to a real object with 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
它已被弃用。
Don't use scriptProperties
it's deprecated.
这篇关于如何从Google Apps脚本项目属性中存储和检索对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!