在d3.js中从外部文件中未定义JSON数据?

时间:2015-09-17 17:07:50

标签: javascript json d3.js

我正在开发一个从外部JSON文件中读取数据的d3.js应用程序。我觉得我已经尝试了所有的东西,但每当我尝试加载数据并在console.log中显示它时,console.log会将数据显示为undefined。我在Firefox上运行了一个带有python -m SimpleHTTPServer的Python Web服务器,以避免跨源资源共享问题,但我实际上没有运气将数据导入浏览器。我的代码:

<html>
    <head>
        <meta charset='utf-8'>
        <title>JSON Data Read</title>
    </head>
    <body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>        
        <script>
var dataset;
d3.json('course.json', function(error, json) {
    dataset = json;
    console.log(dataset);
});
        </script>
    </body>
</html>

有什么建议吗?

编辑:JSON文件

{
    "course_id": "Course 1", 
    "prereqs": null, 
    "off_w": null, 
    "name": "Course 1 Title"
}{
    "course_id": "Course 2", 
    "prereqs": null, 
    "off_w": null, 
    "name": "Course 2 Title"
}{
    "course_id": "Course 3", 
    "prereqs": null, 
    "off_w": null, 
    "name": "Course 3 Title"
}

1 个答案:

答案 0 :(得分:3)

您的JSON文件无效JSON:

{
    "course_id": "Course 1", 
    "prereqs": null, 
    "off_w": null, 
    "name": "Course 1 Title"
}/* <-- JSON block ends here, no further content is expected */{
    "course_id": "Course 2", 
    "prereqs": null, 
    "off_w": null, 
    "name": "Course 2 Title"
}{
    "course_id": "Course 3", 
    "prereqs": null, 
    "off_w": null, 
    "name": "Course 3 Title"
}

这是有效的:

[ {
    "course_id": "Course 1", 
    "prereqs": null, 
    "off_w": null, 
    "name": "Course 1 Title"
}, {
    "course_id": "Course 2", 
    "prereqs": null, 
    "off_w": null, 
    "name": "Course 2 Title"
}, {
    "course_id": "Course 3", 
    "prereqs": null, 
    "off_w": null, 
    "name": "Course 3 Title"
} ]

在对象之间添加了[],

错误消息有点神秘。 JSON是 敏感的空格,因此在}之后,您可以拥有所需的空格,而不是另一个{或任何其他非空白字符。

相关问题