【问题标题】:How do I get JSON data from one HTML Apps Script file in another HTML file?如何从另一个 HTML 文件中的一个 HTML Apps 脚本文件获取 JSON 数据?
【发布时间】:2016-03-12 21:45:55
【问题描述】:

我想从 JavaScript 访问的 Apps 脚本项目中名为 data.json.html 的文件中有一些数据。该文件如下所示:

<script>
var data = {"book1":{"1":25, "2":17}, "book2":{"1":37, "2":4, "3":12}};
</script>

我已尝试通过以下方式访问此数据:

尝试 #1

<script type="text/javascript" src="data.json"></script>
<script>
var books = JSON.parse(data);
</script>

尝试 #2

<?!= include("data.json") ?>
<script>
var books = JSON.parse(data);
</script>

这些都不起作用。谁能告诉我这样做的正确方法?

编辑:抱歉,我忘了包含有关“它不起作用”的含义的信息。基本上,数据并没有进入变量,它应该进入,并且没有错误告诉我执行记录中发生了什么。

如果有人想查看完整的脚本,它嵌入在 Google Doc here 中。只需转到“工具”>“脚本编辑器...”即可找到它。

【问题讨论】:

  • 什么是"VerseNums.json"?项目中的文件名?它是一个 HTML 文件吗?它是脚本文件(.gs)吗?我会尝试,&lt;?!= include("data.json") ?&gt; 然后var books = JSON.parse(data);
  • 为什么将文件命名为 data.json.html?可以只将 JSON 数据保存在 JSON 文件中吗?
  • 创建一个新的 AppsScript 项目,然后点击“帮助/欢迎屏幕”,然后点击“Web App”。这会给你一个很好的例子。
  • @SandyGood 抱歉,这是一个错字。应该是“data.json”。
  • @arman1991 主要是为了我自己的利益,所以很清楚文件中的内容。

标签: javascript html json google-apps-script


【解决方案1】:

这可能不是最佳的,但它会起作用。 取决于 html 文件是否在您的域中(然后只需访问它),否则通过 HTTP 请求检索数据。然后用它来找到儿子的位置和长度:

var string = "responseString",
    substring = "book1";

var jsonStr = str.substring(string.indexOf(substring), 100);

如果您知道匹配 book1 的长度为 100,则可以使用此选项。如果您不知道长度,请使用上面的 ton find location of "};"。

然后在下面使用jsonStr获取键值。

//return an array of objects according to key, value, or key and value matching
function getObjects(obj, key, val) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (typeof obj[i] == 'object') {
            objects = objects.concat(getObjects(obj[i], key, val));    
        } else 
        //if key matches and value matches or if key matches and value is not passed (eliminating the case where key matches but passed value does not)
        if (i == key && obj[i] == val || i == key && val == '') { //
            objects.push(obj);
        } else if (obj[i] == val && key == ''){
            //only add if the object is not already in the array
            if (objects.lastIndexOf(obj) == -1){
                objects.push(obj);
            }
        }
    }
    return objects;
}

//return an array of values that match on a certain key
function getValues(obj, key) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (typeof obj[i] == 'object') {
            objects = objects.concat(getValues(obj[i], key));
        } else if (i == key) {
            objects.push(obj[i]);
        }
    }
    return objects;
}

//return an array of keys that match on a certain value
function getKeys(obj, val) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (typeof obj[i] == 'object') {
            objects = objects.concat(getKeys(obj[i], val));
        } else if (obj[i] == val) {
            objects.push(i);
        }
    }
    return objects;
}


var json = '{"glossary":{"title":"example glossary","GlossDiv":{"title":"S","GlossList":{"GlossEntry":{"ID":"SGML","SortAs":"SGML","GlossTerm":"Standard Generalized Markup Language","Acronym":"SGML","Abbrev":"ISO 8879:1986","GlossDef":{"para":"A meta-markup language, used to create markup languages such as DocBook.","ID":"44","str":"SGML","GlossSeeAlso":["GML","XML"]},"GlossSee":"markup"}}}}}';

var js = JSON.parse(json);

//example of grabbing objects that match some key and value in JSON
console.log(getObjects(js,'ID','SGML'));
//returns 1 object where a key names ID has the value SGML

//example of grabbing objects that match some key in JSON
console.log(getObjects(js,'ID',''));
//returns 2 objects since keys with name ID are found in 2 objects

//example of grabbing obejcts that match some value in JSON
console.log(getObjects(js,'','SGML'));
//returns 2 object since 2 obects have keys with the value SGML

//example of grabbing objects that match some key in JSON
console.log(getObjects(js,'ID',''));
//returns 2 objects since keys with name ID are found in 2 objects

//example of grabbing values from any key passed in JSON
console.log(getValues(js,'ID'));
//returns array ["SGML", "44"] 

//example of grabbing keys by searching via values in JSON
console.log(getKeys(js,'SGML'));
//returns array ["ID", "SortAs", "Acronym", "str"] 

【讨论】:

  • 我认为您不明白我的要求。我在 Apps 脚本项目中的一个单独文件中有一个 JSON 数组中的数据。我希望能够从包含我的 JavaScript 的文件中访问该数据。我非常清楚一旦可以访问该数据中的元素,如何访问它。
【解决方案2】:

在这种情况下,您可以使用它来访问本地文件:

function readTextFile(file)
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                alert(allText);
            }
        }
    }
    rawFile.send(null);
}

第一行的文件是路径和文件名。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 2016-04-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-04
    • 2018-11-13
    • 1970-01-01
    相关资源
    最近更新 更多