/ anomaly / graphTest是在views.py中调用我的get_graph方法的url我无法从我的方法中获取json以返回到我的d3.json函数。我怎样才能做到这一点?我尝试做的是与https://github.com/neo4j-examples/movies-python-bolt类似的东西,使用d3.json在图形上显示内容。是因为python版本不同导致我的应用程序与代码示例的工作方式不同?我还打印出了graph [0]的值。它表明graph [0]未定义。
views.py
def get_graph(request):
db = get_db()
results = db.run("MATCH (m:Movie)<-[:ACTED_IN]-(a:Person) "
"RETURN m.title as movie, collect(a.name) as cast ")
nodes = []
rels = []
i = 0
for record in results:
nodes.append({"title": record["movie"], "label": "movie"})
target = i
i += 1
for name in record['cast']:
actor = {"title": name, "label": "actor"}
try:
source = nodes.index(actor)
except ValueError:
nodes.append(actor)
source = i
i += 1
rels.append({"source": source, "target": target})
return render(request, 'anomaly/index.html',{"nodes": nodes, "links": rels})
的index.html
<script type="text/javascript">
var width = 800, height = 800;
var force = d3.layout.force()
.charge(-200).linkDistance(30).size([width, height]);
var svg = d3.select("#graph").append("svg")
.attr("width", "100%").attr("height", "100%")
.attr("pointer-events", "all");
d3.json("/anomaly/graphTEST", function(error, graph) {
if (error) return;
force.nodes(graph.nodes).links(graph.links).start();
var link = svg.selectAll(".link")
.data(graph.links).enter()
.append("line").attr("class", "link");
var node = svg.selectAll(".node")
.data(graph.nodes).enter()
.append("circle")
.attr("class", function (d) { return "node "+d.label })
.attr("r", 10)
.call(force.drag);
// html title attribute
node.append("title")
.text(function (d) { return d.title; })
// force feed algo ticks
force.on("tick", function() {
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
});
});
</script>
调用get_graph方法时返回的Json示例
{"nodes": [{"title": "Apollo 13", "label": "movie"}, {"title": "Tom Hanks", "label": "actor"}, {"title": "Kevin Bacon", "label": "actor"}
更新1: 我目前能够检索数据并成功解析到我的javascript函数,但是当我在javascript函数中打印该值时,它会显示我奇怪的符号,我并不期待。
javascript怪异的json
[{'title': 'Apollo 13', 'label': 'movie'}, {'title': 'Tom Hanks', 'label': 'actor'}, {'title': 'Kevin Bacon', 'label': 'actor'},