gpt4 book ai didi

javascript - d3.js 中的外部文件未定义 JSON 数据?

转载 作者:行者123 更新时间:2023-11-28 19:00:37 25 4
gpt4 key购买 nike

我正在开发一个 d3.js 应用程序,它从外部 JSON 文件读取数据。我觉得我已经尝试了一切,但每次我尝试加载数据并将其显示在 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"
}

最佳答案

您的 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 对空格敏感,因此在 } 之后,您可以拥有任意数量的空格,而不能是另一个 { 或任何其他非空格字符.

关于javascript - d3.js 中的外部文件未定义 JSON 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32636123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com