How to get int array with javascript in play framework template? - javascript

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");

Related

Having Issues with handling Python dictionaries in Javascript flask templates

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
}

How do I set multiple values of a JSON object?

So I've been working on this project but I'm stuck because I can't figure out how I should go about setting the other values of this new JSON object. So basically on the front end I have this:
HTML page view. The 'cat4' ID is the new object I tried to create, and illustrates the error I'm trying to fix. The problem is that I'm having trouble setting the LIMIT value of newly created objects (or multiple values at all). Here is the code where the object is created:
function sendCat()
{
window.clearTimeout(timeoutID);
var newCat = document.getElementById("newCat").value
var lim = document.getElementById("limit").value
var data;
data = "cat=" + newCat + ", limit=" + lim;
var jData = JSON.stringify(data);
makeRec("POST", "/cats", 201, poller, data);
document.getElementById("newCat").value = "Name";
document.getElementById("limit").value = "0";
}
In particular I've been playing around with the line data = "cat=" + newCat + ", limit=" + lim; but no combination of things I try has worked so far. Is there a way I can modify this line so that when the data is sent it will work? I find it odd that the line of code works but only for setting one part of the object.
The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
MDN
I think this is what you want:
const newCat = 'Meow';
const newLimit = 5;
const data = {
cat: newCat,
limit: newLimit
}
console.log(JSON.stringify(data));
What you're referring to as a 'JSON object' is actually just a javascript object, you can make one using object literal syntax. An object literal with multiple properties looks like this:
var data = {
cat: newCat,
limit: lim
};
makeRec("POST", "/cats", 201, poller, JSON.stringify(data));
assuming the fifth parameter to makeRec is supposed to be the POST request body as stringified JSON, as your code seems to imply

Printing JSON Data into innerHTML getting undefined - [object]

Hi guys Im trying to print a list of scores saved within a database, ive got the data as JSON data (see below)
I am trying to print all each object within the "Scores" array using the following code
function showScores() {
var ourRequest = new XMLHttpRequest();
var x, i = "";
ourRequest.open('GET', '/allScores');
ourRequest.onload = function() {
var ourData = JSON.parse(ourRequest.responseText);
for (i in ourData.scores) {
x += ourData.scores[i] + "<br>";
}
document.getElementById("scoresList").innerHTML = x;
};
ourRequest.send();
}
However it is printing out the following
Any help with this is greatly appreciated, thanks guys
This line tries to append a raw object to your HTML string:
x += ourData.scores[i]
Javascript can’t magically parse this into HTML for you, so it just outputs [object Object].
You need to build a string from the individual parts of this object and print that instead. For example:
Note that you should not use for ... in with an array
ourData.scores.forEach(function (score) {
x += `<p>[H] ${score.Home_Team} <b>${score.Home_Score}</b> - <b>${score.Away_Score}</b> ${score.Away_Team} [A]</p>`;
});
Which would output something like this for each score:
[H] Arsenal 2 - 2 Newcastle [A]
Be sure to set x = "" before the loop otherwise the string will still start with undefined.
In case you’re interested: there are more succinct ways of writing this loop. Using Array.map() for instance:
let x = ourData.scores.map(score => {
return `<p>[H] ${score.Home_Team} <b>${score.Home_Score}</b> - <b>${score.Away_Score}</b> ${score.Away_Team} [A]</p>`;
}).join();
This expression does not require initialization of x beforehand.
you can create the elements as string and you can join the entire array and assign it to the innerHTML, as shown below.
You can change the structure, here for example i had made to ul , li you can create table or whatever format.
Note if you want to just append it, since the object you can't directly append it using JSON.stringify which will convert your object into string.
I hope this will solve your issue. Please let me know if any other issue you are facing.
var jsonObj = {scores: [{"Away_Score": 2, "Away_Team": "Newcastle", "Home_Score": 2, "Home_Team": "Arsenal"}, {"Away_Score": 2, "Away_Team": "Napoli", "Home_Score": 4, "Home_Team": "Liverpool"}]}
var html = jsonObj.scores.map(o => {
return `<ul><li>${o.Away_Team}</li><li>${o.Away_Score}</li><li>${o.Home_Team}</li><li>${o.Home_Score}</li></ul>`
})
document.getElementById("todaysData").innerHTML = html.join("")
<div id="todaysData">
</div>

building json in java script dynamically not working

i try to build json structure object dynamically according examples i saw in the net but with no success.
this is the json i try to build:
{
"campaigns": [
{
"campaign_id":,
"profile_id":,
"state":,
"goal":
},
{
"campaign_id":,
"profile_id":,
"state":,
"goal":
}
]
}
and this is the code :
this function called each time there is data to build the campaigns (in the json) element
var campaignsJson ={};
campaignsJson.campaigns =[];
var i = 0;
function buildJson(stateCampaignId,
profile_id,
stateSelectedValue,
dailyImpressionGoalValue,
pacingValue,
segmentGroupTargetsUpdatedataValue,
frequencytypeProfileValue,
frequencysetProfileValue
)
{
campaignsJson.campaigns[i].campaign_id = stateCampaignId;
campaignsJson.campaigns[i].profile_id = profile_id;
campaignsJson.campaigns[i].state = stateSelectedValue;
campaignsJson.campaigns[i].goal = dailyImpressionGoalValue;
i++;
var campaignsJsonstringify = JSON.stringify(campaignsJson);
alert(campaignsJsonstringify);
}
it gives me "cannot set property campaign_id of undefined"
what does it means ?and why ?
Just before
campaignsJson.campaigns[i].campaign_id = stateCampaignId;
add this :
campaignsJson.campaigns[i] = {};
So that there is an object onto which you'll be able to set properties.
Now, please, don't speak of "JSON structure". What you build is a plain standard JavaScript object while JSON is only the string based exchange format.

when saving an array of objects as a JSON, I need to use the following format in Sample.txt to not run into parsing errors:

when saving an array of objects as a JSON, you need to use the following format in Sample.txt to not run into parsing errors:
[{"result":"\"21 inches = 21 inches\"","count":1},{"result":"\"32 inches = 32 inches\"","count":2}]
I'm new to JSON and searching over this for since last 4 days. I tried different approaches of storing an array of objects but no success. My first and simplest try is like this:
function createData() {
//original, single json object
var dataToSave = {
"result": '"' + toLength.innerText +'"',
"count": counter
};
//save into an array:
var dataArray = { [] }; //No idea how to go ahead..
var savedData = JSON.stringify(dataToSave);
writeToFile(filename, savedData); //filename is a text file. Inside file, I want to save each json object with , in between. So It can be parsed easily and correctly.
}
function readData(data) {
var dataToRead = JSON.parse(data);
var message = "Your Saved Conversions : ";
message += dataToRead.result;
document.getElementById("savedOutput1").innerText = message;
}
To make an array from your object, you may do
var dataArray = [dataToSave];
To add other elements after that, you may use
dataArray.push(otherData);
When you read it, as data is an array, you can't simply use data.result. You must get access to the array's items using data[0].result, ... data[i].result...

Categories