Send Python information to a JavaScript file - javascript

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

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.

Related

How can I get sibling value in JS object?

How can I get 'Pivot Grid', when I have 7? Is there method or can you help me with function?
WIDGET_TYPES = {
PIVOT_GRID: {
LABEL: 'Pivot Grid',
ID: 7,
},
DATA_GRID: {
LABEL: 'Grid',
ID: 4,
},
};
you can use Object.values and find
Object.values - will convert your object to array wiht next structure:
[{LABEL: 'Pivot Grid',ID: 7,}, ...]
after conversion you can apply find to new generated array.
In the find method you will pass your id(7) what need to find
then we need to take label from found element of array
const WIDGET_TYPES = {
PIVOT_GRID: {
LABEL: 'Pivot Grid',
ID: 7,
},
DATA_GRID: {
LABEL: 'Grid',
ID: 4,
},
};
const ID = 7;
const foundLabel = Object.values(WIDGET_TYPES).find(i => i.ID === ID)?.LABEL;
console.log('foundLabel: ', foundLabel)

Fill materialize javascript autocomplete data with twig object

I'm working on an application and now I'm messing with the Materialize autocomplete plugin.
Now I would like to parse an array of twig objects (let's say Customers), and to create an array in JS like this one :
var customersAutocomplete = [
{
key: 1,
Title: "John Doe",
label: 'John'},
{
key: 2,
title: "Ulrich",
label: 'John'},
{
key: 3,
label: 'James'}
];
Autocompletion is from a global JS files and looks like this :
$.fn.autocomplete = function (options) {
// Defaults
var defaults = {
data: {customersAutocomplete},
limit: Infinity,
onAutocomplete: null,
minLength: 1
};
Adding to #RaymondA's comment, you can use Twig to do that directly in your template if your customers object has the right structure already :
<!-- views/your.view.html.twig -->
<script>
customersAutocomplete = {{ customers|json_encode() }};
</script>
And then use customersAutocomplete in your js file :
$.fn.autocomplete = function (options) {
// Defaults
var defaults = {
data: customersAutocomplete,
limit: Infinity,
onAutocomplete: null,
minLength: 1
};

AngularJS: how do i get data into an object and array?

i am trying to get data out of a spreadsheet into an array. I have already stored the data in javascript variables. But now i need those varriables to get stored as an obect in my array. here is my code:
this.json = function(){
jQuery.getJSON("http://cors.io/?u=https://spreadsheets.google.com/feeds/list/1l4XTKaLZihj5WDRuZJE5Y7RQ7Cr7SD_-tH0ctwhizWc/od6/public/values?alt=json").success(function(data) {
console.log(data.feed.entry);
//try
for (var i = 0; i < data.feed.entry.length; i++) {
var id = data.feed.entry[i].gsx$id.$t;
var name = data.feed.entry[i].gsx$name.$t;
var price = data.feed.entry[i].gsx$price.$t;
var notcompatiblewith = data.feed.entry[i].gsx$notcompatiblewith.$t;
this.parts[i] = {"id": id, "name": name, "price": price, "comp": notcompatiblewith, "canAdd": true, "added": false};
};
});
};
i call the function this.json in my html with ng-init="myctrl.json()" and it calls it perfectly. in my console on inspect element i get the error: 'Uncaught TypeError: Cannot set property '0' of undefined'
my array should look like this if it is initialised well:
{
id: 1,
name: 'vitamine A',
price: 3,
canAdd: true,
added: false,
comp: [2, 5]
},
{
id: 2,
name: 'vitamine B',
price: 5,
canAdd: true,
added: false,
comp: [1, 3]
},
{
id: 3,
name: 'vitamine C',
price: 2,
canAdd: true,
added: false,
comp: [2]
},
{
id: 4,
name: 'Opium',
price: 20.95,
canAdd: true,
added: false,
comp: []
},
{
id: 5,
name: 'steroids',
price: 12.5,
canAdd: true,
added: false,
comp: [1]
}
edit: the array parts in initialised under my controller like this
var parts = [];
and is declared in my controller as
this.parts = parts;
When you call this it refers to jQuery. Therefor parts does not exist.
Also, you're doing it wrong. You should use a service for it, and in the service there's a angular's $http for handling ajax requests.
In your way you're not using angular correctly.
Read here: https://docs.angularjs.org/guide/services
You need to initialize this.parts variable with empty Array object:
this.json = function(){
jQuery.getJSON("http://cors.io/?u=https://spreadsheets.google.com/feeds/list/1l4XTKaLZihj5WDRuZJE5Y7RQ7Cr7SD_-tH0ctwhizWc/od6/public/values?alt=json").success(function(data) {
console.log(data.feed.entry);
this.parts = []; // <-- this line was added
// skipped
});
};
Also you can use push method of Array instead of this.parts[i] = ...:
this.parts.push({"id": id, ... });
Have you tried :
this.parts[i].push({"id": id, "name": name, "price": price, "comp": notcompatiblewith, "canAdd": true, "added": false});
Because :
this.parts[i] = {"id": id, "name": name, "price": price, "comp": notcompatiblewith, "canAdd": true, "added": false};
This will end up assigning only one value to array.Everytime array will get upadated of latest value and deleting previous value.

Convert JSON into Array of JavaScript Objects

I got a JSON result from PHP that looks like this below. I need to convert it into an array of objects like shown at the bottom.
How can I achieve this?
What I have
Milestones JSON
[
{
"id":0,
"name":"None"
},
{
"id":1,
"name":"Milestone 1"
},
{
"id":2,
"name":"Milestone 2"
},
{
"id":3,
"name":"Milestone 3"
},
{
"id":4,
"name":"Milestone 4"
}
]
What I need
Milestones Array Of OBjects
var taskMilestonesArray = [{
id: 0,
name: 'None',
},
{
id: 1,
name: 'Milestone 1',
},
{
id: 2,
name: 'Milestone 2',
},
{
id: 3,
name: 'Milestone 3',
},
{
id: 4,
name: 'Milestone 4',
}];
UPDATE
I just realized they are both in almost exact same format already. I just need to pass the array of objects into a library that expects it to be in that format and I don't think I can pass the JSON in.
If you have that JSON in a string (for the sake of the example, I will assume you have a variable named yourJsonString that holds your json), you can parse it:
var taskMilestonesArray = JSON.parse(yourJsonString);
Use JSON.parse api to convert json string to the javascript object.
var taskMilestonesArray = JSON.parse('< milestones json string >');

How to store all array value to one array?

Title is a bit 'misleading, basically I'm trying to replicate an array like this:
'columns': [
{ id: 1, name: 'Operator1' },
{ id: 2, name: 'Operator2' }
]
in one variable:
var myMap = {id: ['0', '1'], name:['Operator1', 'Operator2']}
alert(myMap.id[0]);
The problem's that columns doesn't get the value of myMap, maybe I'm wrong with the array struct? See this code:
Essentially the result that's a I want achieve is this:
'multiColAgendaWeek': {
'type': 'multiColAgenda',
'duration': { weeks: 1 },
'columns': myMap
}
If instead I pass myMap like myMap.id or myMap.Name I get:
undefined
on my fullcalendar.
What am I doing wrong?
PS: I'm using this class extension: https://github.com/mherrmann/fullcalendar-columns/
Image explain:
If I use the myMap array as columns: myMap
Simple map function to convert it.
var myMap = {id: ['0', '1'], name:['Operator1', 'Operator2']};
var updated = myMap.id.map(function (val, ind) {
return { "id" : val, "name" : myMap.name[ind] };
});
console.log(updated);
Still would be better to do it on wherever the data is being generated.

Categories

Resources