With this line of code in python I created JSON containing multiple messages:
notification = [{
'message': 'This is the homepage',
'username': 'User',
'room': 'Home',
'timestamp': '11:59'
},
{
'message': 'Hello World!',
'username': 'User',
'room': 'Home',
'timestamp': '12:00'
}]
return render_template("chat.html", messages = notification)
Now I would like to print all the messages on the webpage, so I sent all the information to javascript. But when the output of the following script returns an empty string.
const message = `{{messages}}`;
console.log(message);
Why is the string empty?
What you are passing in the notification variable isn't actually JSON, it's a Python list. You need to use json.dumps to convert it to an actual JSON string.
Then in your JS you will need to wrap the string in quotes (single quotes best as JSON uses double quotes) so that your JS is syntactically valid. You can then even use Javascript's JSON.parse to convert it to a JS array:
const message = '{{messages}}' ;
console.log(JSON.parse(message) );
Try passing the notification as json to the template
Flask
return render_template("chat.html", messages = json.dumps(notification))
Template
const message = JSON.parse('{{messages | tojson | safe}}');
console.log(message)
Related
In order to pass template variables to Amazon SES, templateData needs to be in the form of a string with escaped quotes, as the following:
"TemplateData": "{ \"subject\": \"mySubject\", \"date\": \"myDate\", \"header\": \"myHeader\", \"message\": \"myMessage\" }"
I need to pass data from a firestore document into these template values. I have tried using ES6's Template strings but the string is not being accepted as valid:
"TemplateData": `{ \"subject\": \"${createdData.subject}\", \"date\": \"${createdData.date}\", \"header\": \"${createdData.header}\", \"message\": \"${createdData.message}\" }`
Any ideas?
This should do it.
const createdData = {
subject: '1',
date: '2',
header: '3',
message: '4'
}
const string = JSON.stringify(createdData)
const escapedString = JSON.stringify(string)
I am consuming a webservice in node js and it returns me the response in this strange format. I have to extract certain values by passing the key names and I would like to convert the response to a JSON for ease of parsing. How should I go about it ?
This is what I get from the webservice
Data Source=*******;Initial Catalog=****;User ID=*******;Password=
*******;MultipleActiveResultSets=True;Min Pool Size=5;Max Pool Size=5000;Conn
ect Timeout=180;Application Name=*****
I want to extract DataSource , UserID, Password.
Dario's answer basically does the trick, but it's worth knowing that Node's querystring module does this sort of stuff "for free".
The code
const qs = require('querystring');
const s = `Data Source=*******;Initial Catalog=****;User ID=*******;Password=*******;MultipleActiveResultSets=True;Min Pool Size=5;Max Pool Size=5000;Connect Timeout=180;Application Name=*****`;
console.log(qs.parse(s, ';', '='));
outputs:
{ 'Data Source': '*******',
'Initial Catalog': '****',
'User ID': '*******',
Password: '*******',
MultipleActiveResultSets: 'True',
'Min Pool Size': '5',
'Max Pool Size': '5000',
'Connect Timeout': '180',
'Application Name': '*****' }
You can easily parse it with String split:
const obj = response.split(';', 2).reduce((json, pair) => {
const tokens = pair.split('=', 2);
json[tokens[0]] = tokens[1];
return json;
}, {});
You can manipulate it, deleting or extracting values, and finally encoding it in JSON with JSON.stringify(obj).
Note: as Oleg V. Volkov comments, if the source string contains delimeters (';' and '=') in key or value, it will don't work.
If the returned pattern is constant, it can be achieved using regexp:
var result = str.match(/Source=(.*);Initial.*ID=(.*);Password=(.*);Multiple/)
And then take your desired values from matched groups.
DataSource = result[1];
UserId = result[2];
Password = result[3];
I have the following javascript that sends data to a PHP function:
<script>
var mydata = {
id:123,
name: 'mike',
orders: []
};
$.ajax({
type: 'POST',
url: 'test.php',
data: {save_data:mydata},
success: function(data) {
alert('php received: ' + data);
}
});
</script>
and my test.php file contains the following code:
<?php
if (isset($_POST['save_data'])) {
$json = json_encode($_POST['save_data']);
echo $json; // just to check what has been received
exit();
}
?>
What I expect to received from PHP is:
{"id":"123","name":"mike","orders":"[]"}
What I got back is {"id":"123","name":"mike"}
Notice that orders array has been eliminated from the output. No place holder for it. I tried adding some dummy elements in the array, and that worked fine, and I received the array back with the elements.
I need PHP to receive the json object as is, even if it contains empty arrays.
How can I do that?
The JSON object is created inside PHP. Before then you just have form data.
jQuery will encode form data in a PHP-friendly style.
If you give it:
data: { foo: [1, 2, 3] }
It will convert that to:
foo[]=1&foo[]=2&foo[]=3
(although it will percent encode the [])
You get a key=value pair for each value.
If you have an empty array then you don't have any values, so you don't get any key=value pairs.
There is no way to encode "an empty array" using PHP's extensions to the form url encoding syntax.
You have two basic options:
Tell PHP about what data structure you want to create in advance and have it fill in the empty arrays.
Generate the JSON on the client
It is not error of PHP. It cause by Jquery will igrone empty array when send it to server. So you have to parse array in 'orders' key to string JSON before send
var mydata = {
id:123,
name: 'mike',
orders: []
};
Change to
var mydata = {
id:123,
name: 'mike',
orders: JSON.stringify([])
};
I'm trying to collect strings I send from AngularJS to a NodeRED array. The AngularJS code looks like this
this.user =
{
medName1: '',
medTime1: ''
},
{
medName2: '',
medTime2: ''
},
{
medName3: '',
medTime3: ''
};
I'm collecting form data in medName1, medTime1,.. and so on. I'm trying to send this data, over websocket, one by one to NodeRED using the following code
this.register = function() {
$scope.sock.send(this.user.medName1);
$scope.sock.send(this.user.medTime1);
$scope.sock.send(this.user.medName2);
$scope.sock.send(this.user.medTime2);
$scope.sock.send(this.user.medName3);
$scope.sock.send(this.user.medTime3);
}
register() is called when I click on "submit" button.
My question is - How do I store these strings in a nodeRED array?. Because the way I'm sending it, the string always gets stored in array index 0, overwriting the previous string. I also tried
$scope.sock.send(JSON.stringify(this.user));
but it sends the entire thing as a string to nodeRED which then makes it impossible to extract the values assigned to medName1, medTime1, and so on.
Can anyone please suggest a way!.. I'll really appreciate your help.
If you send the json.stingify version, you can then use a JSON node in your Node-RED flow to convert it back to the JavaScript object you want.
First, make your this.user an actual array:
this.user =[
{
medName1: '',
medTime1: ''
},
{
medName2: '',
medTime2: ''
},
{
medName3: '',
medTime3: ''
}];
Then, send the this.user array in a single step just as you mentioned:
this.register = function() {
$scope.sock.send(JSON.stringify(this.user));
}
Then, in NodeRED use this:
var user_array = JSON.parse( the_serialized_array );
I have a JSON string as follows:
[
{"TypeName":"Double","TypeID":14},
{"TypeName":"Single","TypeID":43},
{"TypeName":"Family","TypeID":7}
]
It is generated after calling this function in KnockOut:
self.save = function() {
var dataToSave = $.map(self.lines(), function(line) {
return line.product() ? {
TypeName: line.category().TypeName,
TypeID: line.category().TypeID
: undefined
});
alert(JSON.stringify(dataToSave));
However, I want to add 3 more pieces of information to the model, before posting it back to my server - to also send Name, Email and Tel:
{
"Name":"Mark",
"Email":"me#me.com",
"Tel":"0123456789",
"Rooms":
[
{"TypeName":"Double","TypeID":14},
{"TypeName":"Single","TypeID":43},
{"TypeName":"Family","TypeID":7}
]
}
Is there a proper way of adding this information to the JSON, or is it just as simple as:
var toSend = "{\"Name\":\"Mark\":\"Email\":\"me#me.com\", \"Tel\":\"0123456789\",\"Rooms\":"
+ JSON.stringify(dataToSave) + "}";
Thank you,
Mark
Parse your JSON string using JSON.parse into a valid JS object, add the data to the object as needed, then JSON.stringify it back. A JSON string is just a representation of your data, so you shouldn't rely on modifying it directly.
Why encode to JSON and then modify the resulting string when you can pass the structure you actually want to the JSON encdoder?
var toSend = JSON.stringify({
Name: "Mark",
Email: "me#me.com",
Tel: "0123456789",
Rooms: dataToSave
});