2016-08-02 2 views
1

Я создаю приложение с Flask и Python, и я хочу передать некоторые из моих результатов, сгенерированных Python, в JSON, чтобы их можно было визуализировать с помощью D3 под жидкостью контейнера. Для этого я пытаюсь использовать метод Jinja var myjson = {{jsonDict|tojson }};. Здесь jsonDict - это переменная в моем коде Python, которая является строкой dict, где одинарные кавычки были заменены двойными кавычками с регулярным выражением, так что он выглядит как правильный JSON. Я также использую метод JS root = JSON.parse(myjson);. Я считаю, что сочетание этих двух должны решить мою проблему, но когда я запускаю код, однако я получаю сообщение об ошибке:Проблемы с разбором JSON для D3

(index):2222  
Uncaught SyntaxError: Unexpected token y in JSON at position 0 
uo @ d3.v3.min.js:3 
i @ d3.v3.min.js:1 

Вот шаблон D3, который я пытаюсь использовать: http://bl.ocks.org/mbostock/7607535

Вот моя реализация этого D3 (только соответствующий скрипт):

<script> 

var margin = 20, 
    diameter = 960; 

var color = d3.scale.linear() 
    .domain([-1, 5]) 
    .range(["hsl(152,80%,80%)", "hsl(228,30%,40%)"]) 
    .interpolate(d3.interpolateHcl); 

var pack = d3.layout.pack() 
    .padding(2) 
    .size([diameter - margin, diameter - margin]) 
    .value(function(d) { return d.size; }) 

var svg = d3.select("#dan").append("svg") //#dan is name of my container fluid 
    .attr("width", diameter) 
    .attr("height", diameter) 
    .append("g") 
    .attr("transform", "translate(" + diameter/2 + "," + diameter/2 + ")"); 

//this is the part of the code I have added // 
var myjson = {{ jsonDict|tojson }}; 
root = JSON.parse(myjson); 
//this is the part of the code I have added //  

d3.json("root", function(error, root) { 
    if (error) throw error; //this is index 2222 

    var focus = root, 
     nodes = pack.nodes(root), 
     view; 

    var circle = svg.selectAll("circle") 
     .data(nodes) 
    .enter().append("circle") 
     .attr("class", function(d) { return d.parent ? d.children ? "node" : "node node--leaf" : "node node--root"; }) 
     .style("fill", function(d) { return d.children ? color(d.depth) : null; }) 
     .on("click", function(d) { if (focus !== d) zoom(d), d3.event.stopPropagation(); }); 

    var text = svg.selectAll("text") 
     .data(nodes) 
    .enter().append("text") 
     .attr("class", "label") 
     .style("fill-opacity", function(d) { return d.parent === root ? 1 : 0; }) 
     .style("display", function(d) { return d.parent === root ? "inline" : "none"; }) 
     .text(function(d) { return d.name; }); 

    var node = svg.selectAll("circle,text"); 

    d3.select("#dan") 
     .style("background", color(-1)) 
     .on("click", function() { zoom(root); }); 

    zoomTo([root.x, root.y, root.r * 2 + margin]); 

    function zoom(d) { 
    var focus0 = focus; focus = d; 

    var transition = d3.transition() 
     .duration(d3.event.altKey ? 7500 : 750) 
     .tween("zoom", function(d) { 
      var i = d3.interpolateZoom(view, [focus.x, focus.y, focus.r * 2 + margin]); 
      return function(t) { zoomTo(i(t)); }; 
     }); 

    transition.selectAll("text") 
     .filter(function(d) { return d.parent === focus || this.style.display === "inline"; }) 
     .style("fill-opacity", function(d) { return d.parent === focus ? 1 : 0; }) 
     .each("start", function(d) { if (d.parent === focus) this.style.display = "inline"; }) 
     .each("end", function(d) { if (d.parent !== focus) this.style.display = "none"; }); 
    } 

    function zoomTo(v) { 
    var k = diameter/v[2]; view = v; 
    node.attr("transform", function(d) { return "translate(" + (d.x - v[0]) * k + "," + (d.y - v[1]) * k + ")"; }); 
    circle.attr("r", function(d) { return d.r * k; }); 
    } 
}); 

d3.select(self.frameElement).style("height", diameter + "px"); 

</script> 

Как вы можете видеть, я заменил оригинальный JS строки из кода D3:

d3.json("flare.json", function(error, root) { 
    if (error) throw error; 

с:

var myjson = {{ jsonDict|tojson }}; 
    root = JSON.parse(myjson); 

    d3.json("root", function(error, root) { 

Поскольку у меня есть мой код теперь, если я осмотреть страницу, то svg появляется на веб-странице в нужном месте, но он пустой.

Я новичок в D3 и Javascript. Любая помощь приветствуется! Спасибо!

EDIT - консольные журналы

если я console.log (myjson), консоль выводит строку в формате JSON должным образом (см ниже)

если я console.log (корень), то консоль печатает

Object {children: Array[2], name: "flare"} 
children:Array[2] 
name:"flare" 
__proto__:Object 
__defineSetter__: __defineSetter__() 
__lookupGetter__:__lookupGetter__() 
__lookupSetter__:__lookupSetter__() 
constructor:Object() 
hasOwnProperty:hasOwnProperty() 
isPrototypeOf:isPrototypeOf() 
propertyIsEnumerable:propertyIsEnumerable() 
toLocaleString:toLocaleString() 
toString:toString() 
valueOf:valueOf() 
get __proto__:__proto__() 
set __proto__:__proto__() 

Таким образом, кажется, что метод JSON.parse не удается мне как-то.

EDIT - моя JSON строка, которая передается из Python в var myjson

{"name": "flare", "children": [{"name": "concept0", "children": [{"name": "intermediate host", "size": 700}, {"name": "abstrusus brevior", "size": 700}, {"name": "stage larva", "size": 700}, {"name": "anterior extremity", "size": 700}, {"name": "crenosoma vulpi", "size": 700}]}, {"name": "concept1", "children": [{"name": "infected cat", "size": 700}, {"name": "abstrusus infection", "size": 700}, {"name": "domestic cat", "size": 700}, {"name": "feline aelurostrongylosis", "size": 700}, {"name": "cat infect", "size": 700}]}]} 

для исходного текста console.log(myjson)

{"name": "flare", "children": [{"name": "concept0", "children": [{"size": 700, "name": "intermediate host"}, {"size": 700, "name": "abstrusus brevior"}, {"size": 700, "name": "stage larva"}, {"size": 700, "name": "anterior extremity"}, {"size": 700, "name": "crenosoma vulpi"}]}, {"name": "concept1", "children": [{"size": 700, "name": "infected cat"}, {"size": 700, "name": "abstrusus infection"}, {"size": 700, "name": "domestic cat"}, {"size": 700, "name": "feline aelurostrongylosis"}, {"size": 700, "name": "cat infect"}]}]} 

EDIT - Я думаю, что проблема может быть видна в console.log(root). Я проверил другие визуализаций D3 и журнал обычно должен выглядеть следующим образом:

Object {name: "flare", children: Array[5]} 
children: Array[5] 
depth:0 
name:"flare" 
r:470 
value:21000 
x:470 
y:470 
__proto__:Object 
+1

используйте console.log (root), чтобы узнать, какой корень находится в консоли разработчика любого браузера, который вы используете. Убедитесь, что root является правильным JSON, и в нужном формате D3 ожидает. –

+0

console.log (root) отображается как «Объект», но console.log (myjson) правильно печатает строку JSON (но не определяет ее как объект или что-то еще). Я использовал JSON.parse раньше на этих же данных (но другой код D3), и он работал нормально. Думаю, мне нужен другой метод, чтобы он читался как JSON? Спасибо за ваш вклад! – SnarkShark

+0

Можете ли вы поделиться строкой JSON? Похоже, что формат может быть недействительным. – Owen

ответ

1

Поскольку вы уже отдает ваш JSON к вашему клиенту с помощью приложения колбы нет необходимости использовать метод d3.json() d3 в. d3.json() по существу является запросом ajaxGET, который запрашивает файл с сервера.

d3.json(url[, callback])

Creates a request for the JSON file at the specified url with the mime type "application/json". If a callback is specified, the request is immediately issued with the GET method, and the callback will be invoked asynchronously when the file is loaded or the request fails; the callback is invoked with two arguments: the error, if any, and the parsed JSON. The parsed JSON is undefined if an error occurs. If no callback is specified, the returned request can be issued using xhr.get or similar, and handled using xhr.on.

У вас уже есть данные, хранящиеся в переменной на вашем javascript, поэтому не нужно было запрашивать ее с сервера.
Также, когда вы пытались запросить его, вы проходили недопустимый URL-адрес.
Снятие функции d3.json() и просто запуск остальной части кода должен работать.

Смежные вопросы