1

所以我正在使用googlesheets。他们有一个使用谷歌应用脚​​本https://developers.google.com/apps-script/guides/sheets的脚本编辑器。

基本上是JavaScript

我想创建一个函数来运行一个输出我特别想要的 JSON 文件。例如文件外:

{"meta":{"code":200,"disclaimer":"Usage subject to terms: https:\/\/fake-website.com\/terms"},"response":{"date":"2020-04-30T12:37:54Z","base":"X","rates":{"X":1,"F":0.9199812,"K":0.79896235,...}}}

我想访问 F 的速率。所以当我调用我的函数时,它输出 0.9199812。

我写的函数是这样的:

function IMPORTJSON(url,xpath){
  try{
    // Funktion um in dem sheet das abzurufen /rates/F
    let res = UrlFetchApp.fetch(url);
    //get the url
    let content = res.getContentText();
    // get the content
    let json = Json.parse(content);
    //show content

    let patharray = xpath.split(".")
    //enables me to use dots to walk down the filepath

    for( let i=0;i<patharray.lenght;i++){
    //loop to only show what excactly I want out of the file
      //json becomes what I want out of the file
      json = json[patharray[i]];
    } 

  //check whether json is an object
    if(typeof(json) === "undefined"){
        return "Node Not Available"; // In case I don't get an response
      } else if(typeof(json) === "object"){
          let tempArr = [];
      //Creation of an array

          for (let obj in json){
        //filling the array with name and rate
            tempArr.push([obj, json[obj]]);
          }
          return tempArr;
      } else if(typeof(json) !== "object") {
          return json;
      }
     }

  catch(err){
    return "Error getting JSON data";
    }
}

我试图这样称呼它: IMPORTJSON(myurl, rates.F) 但我的工作表告诉我解析公式时出错...该链接肯定有效,因此我的调用 (rates.F) 必须有错误或者用我定义呼叫的方式。请帮忙。

4

1 回答 1

1

获取是一个异步任务,需要时间来完成,所以只有在那个时间之后let res = UrlFetchApp.fetch(url);才有价值。但是其他代码将在res值解析为有意义的东西之前立即运行。要使函数成为异步函数并为异步任务使用await关键字,基本上await意味着在这里等待并且在得到结果之前不要继续前进,因此您可以像这样编写函数:

async function IMPORTJSON(url,xpath){
  try{
    // Funktion um in dem sheet das abzurufen /rates/F
    let res = await UrlFetchApp.fetch(url);
    //get the url
    let content = await res.getContentText();
    // get the content
    let json = JSON.parse(content);
    //show content

    let patharray = xpath.split(".")
    //enables me to use dots to walk down the filepath

    for( let i=0;i<patharray.lenght;i++){
    //loop to only show what excactly I want out of the file
      //json becomes what I want out of the file
      json = json[patharray[i]];
    } 

  //check whether json is an object
    if(typeof(json) === "undefined"){
        return "Node Not Available"; // In case I don't get an response
      } else if(typeof(json) === "object"){
          let tempArr = [];
      //Creation of an array

          for (let obj in json){
        //filling the array with name and rate
            tempArr.push([obj, json[obj]]);
          }
          return tempArr;
      } else if(typeof(json) !== "object") {
          return json;
      }
     }

  catch(err){
    return "Error getting JSON data";
    }
}

于 2020-04-30T15:57:30.557 回答