问题描述
我正在尝试使用此处找到的方法(请参阅投票最多的答案): Google Apps Script Fastest way to find a row?
我目前正在使用它,但是当我替换下面的代码时,我想尝试上面的链接方法
function AutoPopulate (evalue)
{
//uses google drive file irretator reads in JSON file and parses it to a Javascript object that we can work with
var iter = DriveApp.getFilesByName("units.json");
// iterate through all the files named units.json
while (iter.hasNext()) {
// define a File object variable and set the Media Tyep
var file = iter.next();
var jsonFile = file.getBlob().getDataAsString();
// log the contents of the file
//Logger.log(jsonFile);
}
var UnitDatabase = JSON.parse(jsonFile);
//Logger.log(UnitDatabase);
//Logger.log(UnitDatabase[1027]);
return UnitDatabase[evalue];
}
使用此代码:
function AutoPopulate (evalue)
{
//this method did not work for me but should have according to stackflow answer linked above I am trying to understand why or how I can find out why it may have thrown an error
var jsonFile = DriveApp.getFilesByName("units.json").next(),UnitDatabase = UnitDatabase.getBlob().getDataAsString();
return UnitDatabase[evalue];
}
我在执行过程中遇到错误,指示在JSON中位置0处有%,无论如何我都不改变JSON文件的方法之间,所以我不明白为什么顶部方法起作用而底部方法不起作用?
有关更多信息,代码背后的想法是,我在电子表格中有一个单元编号和型号列表。然后,我将其转换为JSON文件,但是只有在将新单元添加到舰队时才完成此操作。据我了解,可以将整个JSON文件解析为一个javascript对象,从而可以更快地处理数据集。使用此javascript对象,以便当用户输入UNIT#时,将根据JSON文件自动填充MODEL#。
我无法共享JSON文件,因为它包含客户信息。
解决方法
您的代码无法正常工作有两个原因:
- 您在
UnitDatabase = UnitDatabase.getBlob()...
行中有错字-应该是UnitDatabase = jsonFile.getBlob()...
- 如果您想从json文件中检索嵌套对象,则需要parse JSOn-否则它被认为是字符串,并且您无法访问嵌套结构
修改后的工作代码:
function AutoPopulate2 (evalue)
{
var jsonFile = DriveApp.getFilesByName("units.json").next();
var UnitDatabase = JSON.parse(jsonFile.getBlob().getDataAsString());
return UnitDatabase[evalue];
}
请注意,只有在驱动器上有"units.json"
文件并且evalue
是此json的有效第一级嵌套对象的情况下,此代码才有效。