So I am building a web application using flask that can track mutiple vehicles and provide updates. The python script helps gather all the data and puts them in a dictionary.
I am sending this dictionary over to the index.html with the javascript code within the HTML that initializes a map and places markers based on the coordinates received from python.
The issue I am having is this dictionary is not being parsed properly in js and as a result I get no data.
Right now I have the {{truck_dict}} placeholder to hold the dict object from python in the html.
PS. I am not the best at JS so dont judge XD
#Python Code
return render_template('pages/index.html', trucks = truck.driver_locator(truck.locations()))
#Even when I jsonify/json.dump the variable in the trucks object, nothing happens
#JS Code
var truck_dict = {{trucks | tojson}}
var i;
for (var key in truck_dict){
var value = truck_dict[key];
var geojson = {
type: 'FeatureCollection',
features: [{
type: 'Feature',
geometry: {
type: 'Point',
coordinates: value
},
properties: {
title: 'Mapbox',
description: '1303'
}
}]
};
SAMPLE OUTPUT of the python generated dict
{'1301': [43.1220307, -78.9352247], '1302': [42.3107737, -77.2519131], '1304': [40.3809016, -74.5665863], '1305': [40.2453049, -74.5707928], '1303': [39.6435448, -75.9325289]}
Here is the output:
var truck_dict = {'1301': [43.1220307, -78.9352247], '1302': [42.3107737, -77.2519131], '1304': [40.3809016, -74.5665863], '1305': [40.2453049, -74.5707928], '1303': [39.6435448, -75.9325289]};
for (var i in truck_dict) {
console.log(i, truck_dict[i]);
}
output:
1301 [43.1220307, -78.9352247]
1302 [42.3107737, -77.2519131]
1303 [39.6435448, -75.9325289]
1304 [40.3809016, -74.5665863]
1305 [40.2453049, -74.5707928]
So, you need to log truck_dict, like:
var truck_dict = {{trucks | tojson}};
console.log(trucks);
console.log(truck_dict);
You're trying to index a dictionary.Using truck_dict[I] doesn't work here because your indices are not numbers (not possible in js anyway).
You need to access dictionary elements with their keys (ex. truck_dict['1301'] or truck_dict.1301) NOT indexes. If you want to iterate over each key (which you can use to reference the value mapped to that key), use:
for(var key in truck_dict) {
var value = truck_dict[key];
// do what you need with value and key here
}
Related
I'm retrieving an OSM Json from an overpass call, to obtain a list of features that I have to save on a database. Since the data are very different from one another (for example, some of them do have a a tag called "addr:city", and some of them not), I would like to check if a key exists, and only in that case save the corresponding value. I've found only this question but it's not my case, since I do not know a priori which keys one element will have and which not, and since I'm working with a great load of data, I really can't check the elements one by one and of course I can't write an IF for each case.
Is there a way to solve this? I was thinking something about "if key has null value, ignore it", while looping over the elements, but I don't know if something like that exists
EDIT:
This is my query:
https://overpass-api.de/api/interpreter?data=[out:json][timeout:25];(node[~%22^(tourism|historic)$%22~%22.%22](44.12419,%2012.21259,%2044.15727,%2012.27696);way[~%22^(tourism|historic)$%22~%22.%22](44.12419,%2012.21259,%2044.15727,%2012.27696););out%20center;
and this is the code I'm using to save the data on firebase:
results.elements.forEach(e=>{
var ref = firebase.database().ref('/point_of_interest/');
var key = firebase.database().ref().child('point_of_interest').push().key;
var updates = {};
var data = {
città: e.tags["addr:city"],
tipologia: e.tags["amenity"],
indirizzo: e.tags["addr:street"],
nome: e.tags["name"],
lat: e.lat,
lon: e.lon
}
updates['/point_of_interest/'+key] = data;
firebase.database().ref().update(updates);
})
"results" is the response in json format
You could use something like that:
var attrs = ["addr:city", "amenity", "addr:street", "name"];
var labels = ["città", "tipologia", "indirizzo", "nome"]
var data = { };
attrs.forEach((a, i) => {
if (e.tags[a]) { data[labels[i]] = e.tags[a]; }
});
You could even make this more dynamic, if you can query the attribute names and labels from somewhere.
When I tried to pass a list to the template I got an error.
The list is defined like:
myList: List<Map<String,int[]>>
Now the data of myList is :
[{First Try=[1,0,0,1], Second Try=[1,1,2,2]}, {}]
I use chart.js to show a chart and so I need a int[] as data list.
my view:
#(myList: List[Map[String,Array[Int]]])
var list = #myList;
for(var i=0;i<list.length;i++){
var map = list[i];
for(var key in map){
myFunction(key,map[key]);
}
}
myFunction(string,array){
//I want directly use the array to the chart’s datasets
//others
var myChart = new Chart(chartid, {
type: 'bar',
data: {
labels: [“a”, “b", “c”, ”s”],
datasets: [{
data: array
}]
}
}
But I got error when I try to traversal the List (The error line shown with Chrome debug)
var out = [{First Try=[I#6e37161d, Second Try=[I#5788d8a9}, {}];
// “Uncaught SyntaxError: Invalid or unexpected token”.
I know when directly output array with
System.out.println(array);
in java it will happen with the string like [I#6e37161d, but I don’t know how to deal with it in javascript.How can I use this array?I will be grateful if anyone can help .
Thank you very much.
You can't convert the Java object directly to a Javascript variable like you're attempting to do.
var list = #myList;
That just takes myList.toString() and attempts to set that as a literal Javascript variable. You need to serialize your Java object to JSON first, then you can parse the JSON in Javascript. Like so:
// Java controller code
String myListJson = Json.stringify(Json.toJson(myList));
// Template
#(myListJson: String)
var list = JSON.parse("#myListJson");
I am trying to use the google charts library to plot some time series data which at the moment is some dummy data I pasted into a separate file from my app.
I have an Immutable List looking something like this :
let data = [{"Date":1452457976,"Value":246.712065},{"Date":1452457990,"Value":268.240542}]
I'm trying to convert this to a plain javascript array of arrays, each containing a Date object and a value as follows.
let row_data = data.map( (list_object) => {
let temp_list = Immutable.List();
temp_list = temp_list.push(new Date(list_object.get('Date')));
temp_list = temp_list.push(list_object.get('Value');
return temp_list;
});
export default row_data.toJS();
I'm using this exported value as the input for constructing the data-table for a google chart using the react-google-charts library. The result is that the section of the page has empty content and with nothing rendered without and no errors logged.
import row_data from 'data';
let options = {...};
let rows = row_data;
let columns = [
{
'type': 'date',
'name': 'Date'
},
{
'type': 'number',
'name': 'Latency'
}
]
this.setState({
'rows': rows,
'columns': columns,
'options': options
});
Digging into the stacktrace, it looks like the argument being passed as rows is not of the type array, even though logging the variable gives me the following : Array[<length>] .
I feel like the way I am doing the immutable transformations are very hacky as I just started using the library today. Please do let me know if there is a better way to approach this.
Turns out this is the proper pattern to convert unix timestamps into a Javascript Date object.
let time_labels = data.map( (ts_obj) => {
let d = new Date();
d.setTime(ts_obj.get('Date') * 1000);
return d;
});
This is because the setTime function uses milliseconds.
I have an object which comes back as part of a return data from a REST server. It is part of an item object.
(I don't have control over the REST server so I can't change the data received):
{
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
}
What I want to end up with is some control over this, so that I can display the results when a product is selected in my app. It will appear in a modal. I am using Marionette/Backbone/Underscore/JQuery etc. but this is more of a JavaScript question.
I have tried multiple ways of getting at the data with no success. I would like to be able to have the options in a nested array, but I'd be open to other suggestions...
Basically this kind of structure
var Color=('Red', 'Green', 'Blue', 'Orange')
var Size('Small', 'Medium', 'Large')
The Object structure is fine, just need to be able to translate it to an array and take out the 'Option' keyword
Important to mention that I have no idea what the different options might be when I receive them - the bit after Options: might be any form of variation, color, size, flavour etc.
Loop through the parsed JSON and create new keys on a new object. That way you don't have to create the var names yourself; it's automatically done for you, albeit as keys in a new object.
var obj = {
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
}
function processObj() {
var newObj = {};
for (var k in obj) {
var key = k.split(':')[1].toLowerCase();
var values = obj[k].split(',');
newObj[key] = values;
}
return newObj;
}
var processedObj = processObj(obj);
for (var k in processedObj) {
console.log(k, processedObj[k])
// color ["Red", "Green", "Blue", "Orange"], size ["Small", "Medium", "Large"]
}
Edit: OP I've updated the code here and in the jsfiddle to show you how to loop over the new object to get the keys/values.
Fiddle.
var json = {
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
};
var color = json['Option:Color'].split(',');
var size = json['Option:Size'].split(',');
Try this to do get a solution without hardcoding all the option names into your code:
var x = {
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
};
var clean = {};
$.each(x, function(key, val){ //iterate over the options you have in your initial object
var optname = key.replace('Option:', ''); //remove the option marker
clean[optname] = val.split(","); //add an array to your object named like your option, splitted by comma
});
clean will contain the option arrays you want to create
EDIT: Okay, how you get the names of your object properties like "color", which are now the keys in your new object? Thats the same like before, basically:
$.each(clean, function(key, val){
//key is the name of your option here
//val is the array of properties for your option here
console.log(key, val);
});
Of course we stick to jQuery again. ;)
Description and Goal:
Essentially data is constantly generated every 2 minutes into JSON data. What I need to do is retrieve the information from the supplied JSON data. The data will changed constantly. Once the information is parsed it needs to be captured into variables that can be used in other functions.
What I am stuck in is trying to figure out how to create a function with a loop that reassigns all of the data to stored variables that can later be used in functions.
Example information:
var json = {"data":
{"shop":[
{
"carID":"7",
"Garage":"7",
"Mechanic":"Michael Jamison",
"notificationsType":"repair",
"notificationsDesc":"Blown Head gasket and two rail mounts",
"notificationsDate":07/22/2011,
"notificationsTime":"00:02:18"
},
{
"CarID":"8",
"Garage":"7",
"Mechanic":"Tom Bennett",
"notificationsType":"event",
"notifications":"blown engine, 2 tires, and safety inspection",
"notificationsDate":"16 April 2008",
"notificationsTime":"08:26:24"
}
]
}};
function GetInformationToReassign(){
var i;
for(i=0; i<json.data.shop.length; i++)
{
//Then the data is looped, stored into multi-dimensional arrays that can be indexed.
}
}
So the ending result needs to be like this:
shop[0]={7,7,"Michael Jamison",repair,"Blown Head gasket and two rail mounts", 07/22/2011,00:02:18 }
shop[1]={}
You can loop through your JSON string using the following code,
var JSONstring=[{"key1":"value1","key2":"value2"},{"key3":"value3"}];
for(var i=0;i<JSONstring.length;i++){
var obj = JSONstring[i];
for(var key in obj){
var attrName = key;
var attrValue = obj[key];
//based on the result create as you need
}
}
Hope this helps...
It sounds to me like you want to extract the data in the "shop" property of the JSON object so that you can easily reference all of the shop's items. Here is an example:
var json =
{
"data":
{"shop":
[
{"itemName":"car", "price":30000},
{"itemName":"wheel", "price":500}
]
}
},
inventory = [];
// Map the shop's inventory to our inventory array.
for (var i = 0, j = json.data.shop.length; i < j; i += 1) {
inventory[i] = json.data.shop[i];
}
// Example of using our inventory array
console.log( inventory[0].itemName + " has a price of $" + inventory[0].price);
Well, your output example is not possible. You have what is a list of things, but you're using object syntax.
What would instead make sense if you really want those items in a list format instead of key-value pairs would be this:
shop[0]=[7,7,"Michael Jamison",repair,"Blown Head gasket and two rail mounts", 07/22/2011,00:02:18]
For looping through properties in an object you can use something like this:
var properties = Array();
for (var propertyName in theObject) {
// Check if it’s NOT a function
if (!(theObject[propertyName] instanceof Function)) {
properties.push(propertyName);
}
}
Honestly though, I'm not really sure why you'd want to put it in a different format. The json data already is about as good as it gets, you can do shop[0]["carID"] to get the data in that field.