3

I am new to Python and JavaScript and (attempting) to use cola.js. My HTML form sends information to Python, which turns it into an array of dictionaries.

Class_Name(ndb.Model):
    class_title = ndb.JsonProperty()
def post(self):
    classname = self.request.get('classname') #user inputs 1 classname
    prereq = self.request.get('prereq') #user inputs 1 prereq
    new_dictionary = {}
    new_dictionary [classname] = prereq
    new_class = Class_Name(class_title = new_dictionary) #stores as a dictionary
    new_class.put()

    Class_data = Class_Name.query().fetch() #gets all instances of Class_Name

   *** code that goes in b/w sends back to input form if want to add more classes, else, goes to below code

        output = []
        for a in Class_data:
            jsonprop = a.class_title
            extracted_output = json.dumps(jsonprop)
            output.append(extracted_output)
        template_vars= {'Class_data': output}
        template = jinja2_environment.get_template('template/post.html')
        self.response.write(template.render(template_vars))

This is my basic code so far. I want to use cola.js to turn my information into a graph, basically mapping out each class with its prerequisites. However, the cola.js format is a JavaScript file that looks like this:

graph = {
  nodes: [
  {
    id: 'A'
  }, {
    id: 'B'
  }, {
    id: 'C'
  }
],

links: [
  {
    id: 1,
    source: 'A',
    target: 'B'
  }, {
    id: 2,
    source: 'B',
    target: 'C'
  }, {
    id: 3,
    source: 'C',
    target: 'A'
  }
]
};

Is there any way I can tell JavaScript to get my Python array, and enter the info into the JavaScript file like this?

graph = {
  nodes: [
  {
    id: 'Class1' **will put actual class name
  }, {
    id: 'Class2'
  }
],

links: [
  {
    id: 1,
    source: 'Class1',
    target: 'prereq'
  }, {
    id: 2,
    source: 'Class2',
    target: 'prereq'
  }
]
};

This is a rough code for turning my Python information into the JavaScript format.

nodes_array = []
nodes_dict = {}
links_array = []
links_dict = {}
graph_array = []

#loops through every element
for a in Class_data:
    jsonprop = a.class_title
    extracted_output = json.loads(jsonprop)

for c_class, prereq in extracted_output.iteritems():
    # for the links dictionary  
    counter_link = 1
    # creates {'id':'class1'}
    nodes_dict['id'] = c_class
    #creates [ {'id':'class1'},  {'id':'class2'}]
    nodes_array.append(nodes_dictionary)
    # creates {'id': 'counter', 'source': 'class1', 'target': 'prereq'}
    links_dictionary[id] = counter_link
    counter_link++
    links_dictionary[source] = c_class
    links_dictionary[target] = prereq
    # creates [{'id': 'counter', 'source': 'class1', 'target': 'prereq'}]
    links_array.append(links_dictionary)
    #creating the format --> 'nodes': [  {id: class1}, {id:class2},  {id:class3} ]"
    #creating the format --> 'links': [  {id: 1, source :class2, target :class3} ]"
    graph[nodes] = nodes_array
    graph[links] = links_array
2
  • You can produce the JavaScript file programmatically; but generally a better solution is that the JavaScript would fetch the data using for example jQuery.ajax() Commented Aug 29, 2015 at 8:58
  • probably you are looking for this stackoverflow.com/questions/7020135/… Commented Aug 29, 2015 at 10:30

1 Answer 1

2

Your Python script can use the json module to write the graph to a file in a format that JavaScript understands.

If you do this in Python:

import json

graph = {
    'nodes': [ {'id': 'Class1'}, {'id': 'Class2'} ],
    'links': [
        { 'id': 1, 'source': 'Class1', 'target': 'prereq' },
        { 'id': 2, 'source': 'Class2', 'target': 'prereq' }
    ]
}

with open('graph.js', 'w') as out_file:
  out_file.write('var graph = %s;' % json.dumps(graph))

The result is a file named graph.js, containing this:

var graph = {"links": [{"target": "prereq", "source": "Class1", "id": 1}, {"target": "prereq", "source": "Class2", "id": 2}], "nodes": [{"id": "Class1"}, {"id": "Class2"}]};

If you load graph.js before loading your own JavaScript file, you can refer to the variable graph to use your graph.

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

5 Comments

Thank you for the comments before! I will attempt to do this and see if I run into any trouble.
If you're happy with my answer, would you please accept it?
I updated my code and wanted to know how I can format my dictionary to be like this {id: 'class'} instead of {"id': "class"}, which is what I'm getting from my file. Do you also have any tips for my code? Thanks
There is no semantic difference between { id: 'class' } and { "id": "class" }. JavaScript treats them exactly the same way. As far as the file is concerned, that is the syntax required by JSON. I don't know why the double quotes would bother you, but if they do, you can't use this simple approach. You have to write your own Python code to generate output in your desired format. I suspect that the effort wouldn't be worth it. Your code looks okay to me. if you have specific questions about it, you should probably post another question. Have I answered this question to your satisfaction?
I don't know any JavaScript so I thought that the JavaScript had to have a specific syntax in order for the code to work. Thank you so much for all your help!

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.