首页 > 解决方案 > 将外部 JSON 加载到 HTML

问题描述

我对 HTML 超级陌生,如果这是一个愚蠢的问题,我很抱歉。

我目前的数据是外部 JSON,并调用在 HTML 中加载。而不是加载它,我只想将它复制到 HTML 中并将其保存为其中的一部分。在不更改数据结构的情况下如何做到这一点?

示例数据 JSON:

[
{ 
    "User" : "COMP",
    "Runtime" : 931.216111111
},
{ 
    "User" : "AUTO",
    "Runtime" : 600.404444444
}
]

我在哪里加载它:

// load data
d3.json("data.json", function(error, data) {

    data.forEach(function(d) {
        d.User = d.User;
        d.Runtime = +d.Runtime;
    });

  // scale the range of the data
  x.domain(data.map(function(d) { return d.User; }));
  y.domain([0, d3.max(data, function(d) { return d.Runtime; })]);

我已经查看了答案,但我的问题是如何将其复制到 HTML 中并且仍然能够以相同的方式调用 d.Runtime 和 d.User 参数

标签: htmljsonload

解决方案


在您的 HTML 页面中,您需要添加一个脚本标记来保存 JavaScript。将它放在正文中可能是个好主意,以便在页面加载时执行。

<script type="text/javascript">

</script>

接下来,您需要为脚本标签内的数据定义一个常量。等号后面可以复制粘贴.json文件的内容:

const data = [
  { 
    "User" : "COMP",
    "Runtime" : 931.216111111 
  },
  { 
    "User" : "AUTO",
    "Runtime" : 600.404444444
  }
]

现在您可以在 d3.json 回调中附加您的代码:

data.forEach(function(d) {
    d.User = d.User;
    d.Runtime = +d.Runtime;
});

// scale the range of the data
x.domain(data.map(function(d) { return d.User; }));
y.domain([0, d3.max(data, function(d) { return d.Runtime; })]);

推荐阅读