解析存储在数据库中的json字符串以呈现D3树布局

时间:2017-01-05 16:29:19

标签: javascript d3.js

我正在尝试使用从mysql数据库中存储的字符串中获取的json来填充D3可扩展树布局。

我从mysql中获取json,如下所示:

jQuery.ajax({
            type: "POST",
            url: '../connect/database.php',
            dataType: 'json',
            data: {functionname: 'read_from_database', arguments: [user_id]},
            success: function (obj, textstatus) {
            if( !('error' in obj) ) {
               localStorage.setItem('json_string', JSON.stringify(obj.query_result.stored_json_string));
              }
            else {
               console.log(obj.error);
              }
             }
            });

这会将json字符串设置为本地存储。工作完美。

然后我从本地存储中抓取这个字符串,如下所示:

var json_string = localStorage.getItem('json_string');

这给了我D3布局所需的字符串。它的格式与D3站点上使用的flare.json文件相同。

从数据中呈现树的D3的主要部分是这一部分。我只是从本地存储添加了json_string,并在d3.json调用中使用了JSON.parse。这也是在获取数据后2秒触发,因此我确认json_string确实已加载。

d3.json(json_string, function(json) {
root = JSON.parse(json);
root.x0 = h / 2;
root.y0 = 0;

function toggleAll(d) {
if (d.children) {
  d.children.forEach(toggleAll);
  toggle(d);
}
} 

// Initialize the display to show a few nodes.
root.children.forEach(toggleAll);
toggle(root.children[1]);
toggle(root.children[1].children[2]);
toggle(root.children[9]);
toggle(root.children[9].children[0]);
update(root);
});

但是这会在浏览器中出现以下错误:

GET http://blahblahdotcom/path/tree/%22%7B/%22name/%22:/%22flare/%…%7D,%7B/%22name/%22:/%22Visualization/%22,/%22size/%22:16540%7D]%7D]%7D%22 414 (Request-URI Too Long)
d3.xhr @ d3.js:385
d3.text @ d3.js:395
d3.json @ d3.js:398
load_tree @ tree.html:65
(anonymous) @ tree.html:190
tree.html:67 Uncaught TypeError: Cannot set property 'x0' of null

1 个答案:

答案 0 :(得分:1)

d3.json适用于async loading.json文件。因为您已经加载了JSON,所以不需要使用它。

您可以用它替换jQuery.ajax来电,但假设您想继续使用jQuery加载数据,则可以删除d3.json来电。

var root = JSON.parse(json_string);
// ...

修改

您也在对从服务器加载的obj.query_result.stored_json_string进行字符串化,但它已经是一个字符串,因此这是不必要的,并且需要您必须两次调用JSON.parse才能获得所需的对象

const serverValue = '{"a": "b"}';
console.log('serverValue =', serverValue, typeof serverValue);

// when you stringify a string, you get an escape string
const stringified = JSON.stringify(serverValue);
console.log('stringified =', stringified, typeof stringified);

// the first time that you parse that, you get a string
const firstParse = JSON.parse(stringified);
console.log('firstParse =', firstParse, typeof firstParse);

// the second time that you parse, you get an object
const secondParse = JSON.parse(firstParse);
console.log('secondParse =', secondParse, typeof secondParse);

您应该直接存储stored_json_string

if( !('error' in obj) ) {
  localStorage.setItem('json_string', obj.query_result.stored_json_string);
}