【问题标题】:Can't read json in D3无法在 D3 中读取 json
【发布时间】:2017-05-28 11:47:57
【问题描述】:

我正在尝试使用 D3 库读取 json 文件,但是当我尝试读取 json 时,我收到警报 Null 值(这里我使用警报)。

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Simple venn.js example</title>
</head>

<body>
    <div id="weighted_example"></div>
</body>

<script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>

<script>
d3.json( "file.json", function( json ) {
  alert( "JSON Data: " + json );
});
</script>
</html>

以下是file.json(已经在线验证)

 [{
        "sets": [0],
        "size": 1958
    },
    {
        "sets": [1],
        "size": 1856
    },
    {
        "sets": [2],
        "size": 1297
    },
    {
        "sets": [0, 1],
        "size": 220
    },
    {
        "sets": [2, 0],
        "size": 123
    },
    {
        "sets": [2, 1],
        "size": 139
    }
 ]

我该如何解决这个问题?

【问题讨论】:

  • 在浏览器工具中使用网络选项卡并检查文件是否正在加载,您可能会收到 404
  • file.json 在哪里?是在同一个目录吗?
  • @man-data 你一定是在打赌错误 XMLHttpRequest 无法加载“跨源请求仅支持协议方案:http、data、chrome、chrome-extension、https。”
  • @Dinesh 是的,它们在同一个目录中
  • 该文件是否已加载?您可以在开发人员工具网络选项卡中查看

标签: javascript jquery html json d3.js


【解决方案1】:

如果您在浏览器中运行,则无法加载本地文件。我建议将数据上传到网上某处,例如here,然后使用 d3.json() 请求它。

点赞:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Simple venn.js example</title>
</head>

<body>
    <div id="weighted_example"></div>
</body>

<script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>

<script>
d3.json( "https://gist.githubusercontent.com/kvyb/d482dc15602c34841d4796daa9ed64cb/raw/d737e19c03868adf2f15103fcd98384f4c364785/file.json", function(json) {
  alert( "JSON Data: " + json)
});
</script>
</html>

否则,您可以将其硬编码到您的 html 文件中:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Simple venn.js example</title>
</head>

<body>
    <div id="weighted_example"></div>
</body>

<script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>

<script>
var json =  [{
        "sets": [0],
        "size": 1958
    },
    {
        "sets": [1],
        "size": 1856
    },
    {
        "sets": [2],
        "size": 1297
    },
    {
        "sets": [0, 1],
        "size": 220
    },
    {
        "sets": [2, 0],
        "size": 123
    },
    {
        "sets": [2, 1],
        "size": 139
    }
 ]

alert( "JSON Data: " + json)

</script>
</html>

如果您不介意使用其他库,有一个jquery 解决方案可以在本地加载等等。

【讨论】:

  • Vybrial 我知道如何使用 Jquery,但我需要使用 D3 阅读,因为我正在使用 D3 函数。我不能在本地读取 json。
  • 恐怕只有D3没有办法。
【解决方案2】:

为了让这些文件在本地工作,您需要使用 HTTP 服务器。我个人使用 MAMP for Mac 机器。

【讨论】:

    猜你喜欢
    • 2015-08-01
    • 1970-01-01
    • 2018-08-22
    • 1970-01-01
    • 2018-11-11
    • 1970-01-01
    • 2019-12-14
    • 2013-07-29
    • 2023-03-05
    相关资源
    最近更新 更多