0

I want to make a very simple network graph for some links between documents that I've extracted, and display it in an existing Django application. I've looked at a bunch of Bokeh/Django integrations and things along those lines but nothing seems appropriate. Therefore I've decided to go ahead and try D3. I don't know any Javascript. I copied the template provided here: http://bl.ocks.org/mbostock/2706022 and this is fine for my purposes. All I need to do is to provide my own data. I can build up a list of dictionaries in the view and pass these as a context. I can access that context in the template with {{ data }}. However, what I don't know how to do is to then feed that to the javascript. This is the relevant part that I'll need to change:

var links = [
  {source: "Microsoft", target: "Amazon", type: "licensing"},
  {source: "Microsoft", target: "HTC", type: "licensing"},
  {source: "Samsung", target: "Apple", type: "suit"},
  {source: "Motorola", target: "Apple", type: "suit"},
  {source: "Nokia", target: "Apple", type: "resolved"},
...
  {source: "Nokia", target: "Qualcomm", type: "suit"}
];

This looks like a list of dictionaries. But I don't know, there's some bare words in there so I'm not sure how Javascript sees this thing and how to cast the python context into whatever this is. I imagine something along the lines of

var links = <cast>({{data}})

How do I implement this so that I can pass this D3 code my own data?

1 Answer 1

1

You can build your list of dictionaries and pass it to your template as JSON.
Then parse your JSON string in javascript .

In python, use data = json.dumps(your_list_of_dict) and in javascript, use var links = JSON.parse('{{data}}');. You might need to do something more for the potential quotes issues.

Sign up to request clarification or add additional context in comments.

6 Comments

Yea it looks like there are issues with the quotes. I'll let you know if I fix it.
SyntaxError: JSON.parse: expected property name or '}' at line 1 column 3 of the JSON data
It could be different things depending on your encoding, you can try data = json.dumps(your_list_of_dict).replace(/&quot;/ig,'"');
Ah okay yes. I logged '{{data}}' before sending to JSON and: [{&quot;source&quot;: &quot;Microsoft&quot;, &quot;target&quot;: &quot;Amazon&quot;, &quot;type&quot;: &quot;licensing&quot;}, {&quot;source&quot;: &quot;Microsoft&quot;, &quot;target&quot;: &quot;Someone else&quot;, &quot;type&quot;: &quot;licensing&quot;}]
See previous comment, you just have to replace those &quot; by "
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.