我错过了很多时间来解决这个问题,但运气不好。我知道如何用外部文件呈现d3树,但是如何使用生成的对象来实现。我要让Json对象通过下面的代码:
$.when($.getJSON('data/clinical.json'), $.getJSON('data/industry.json'))
.then(function (a, b) {
return $.extend(a[0], b[0]);
})
.then(function (data) {
var json = JSON.stringify(data);
console.log('['+ json +']');并在d3.json中添加了json
treeJSON = d3.json(json, function (error, treeData) {因此,整个代码部分看起来如下:
function load() {
$.when($.getJSON('data/clinical.json'), $.getJSON('data/industry.json'))
.then(function (a, b) {
return $.extend(a[0], b[0]);
})
.then(function (data) {
var json = JSON.stringify(data);
console.log('['+ json +']');
// Get JSON data
treeJSON = d3.json(json, function (error, treeData) {最有趣的部分是自定义的控制台日志,如右字符串:
[{"text":"Alas","icon":"icons/tree.png","children":[{"text":"CDISC","children":[{"text":"SDTM","children":[{"text":"SDTM 3.1.1","icon":"icons/file.png"},{"text":"SDTM 3.1.3","icon":"icons/file.png"},{"text":"SDTM 3.2","icon":"icons/file.png"}]},{"text":"ADaM"},{"text":"CDASH"}]},{"text":"CDISC"},{"text":"BRIDG"}]}]但我还是有个错误:
GET http://localhost:63342/testMerg/%7B%22text%22:%22Alas%22,%22icon%22:%22…SH%22%7D]%7D,%7B%22text%22:%22CDISC%22%7D,%7B%22text%22:%22BRIDG%22%7D]%7D 404 (Not Found)我尝试从下面的例子中使用string方法:
.then(function (data) {
var json = JSON.stringify(data);
// Get JSON data
treeData = JSON.parse( data );但是有个错误
Uncaught SyntaxError: Unexpected token o所以我放弃了..。有人能帮我吗?
发布于 2016-03-02 04:55:21
问题的出现是因为data是一个对象,并且您试图解析该对象。但是JSON.parse函数需要一个字符串作为参数。
您可以直接分配treeData = data。(不需要解析)。
否则,您应该尝试对对象进行字符串化,然后解析字符串化的json。
var json = JSON.stringify(data);
treeData = JSON.parse(json);
var data = {"text":"Alas","icon":"icons/tree.png","children":[{"text":"CDISC","children":[{"text":"SDTM","children":[{"text":"SDTM 3.1.1","icon":"icons/file.png"},{"text":"SDTM 3.1.3","icon":"icons/file.png"},{"text":"SDTM 3.2","icon":"icons/file.png"}]},{"text":"ADaM"},{"text":"CDASH"}]},{"text":"CDISC"},{"text":"BRIDG"}]};
//treeData = data;
json = JSON.stringify(data);
console.log(JSON.parse(json));
https://stackoverflow.com/questions/35738506
复制相似问题