将外部 JSON 加载到 HTML

Load External JSON into 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 参数

在您的 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; })]);