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)
Related
I am sending the array of dicts from javascript to python via a POST request that looks this way:
mydata.push({
department_id: department_id,
cardgroup_id: cardgroup,
doorgroup_id: doorgroup
});
$.post("data/save-office/"+office, {'data': JSON.stringify(mydata)}, function (data) {
console.log(data);
});
When extracting the payload in python:
departments = request.form.getlist('data')
The output is:
departments = ['[{"department_id":"1","cardgroup_id":"2","doorgroup_id":"2550"},
{"department_id":"2","cardgroup_id":"2","doorgroup_id":"2550"},
{"department_id":"3","cardgroup_id":"2","doorgroup_id":"2550"},
{"department_id":"4","cardgroup_id":"2","doorgroup_id":"2550"}]']
This displayed output is an array of one index and the inside is treated as a string rather than a dictionary.
How can I filter it or send it from javascript so that it can be decoded as an array of dicts not an array of strings?
Without changing your code, the simplest solution is using the json library's load or loads (load safe) method
import json
departments_string = request.form.getlist('data')[0]
departments = json.loads(departments_string)
print(departments)
[{'department_id': '1', 'cardgroup_id': '2', 'doorgroup_id': '2550'},
{'department_id': '2', 'cardgroup_id': '2', 'doorgroup_id': '2550'},
{'department_id': '3', 'cardgroup_id': '2', 'doorgroup_id': '2550'},
{'department_id': '4', 'cardgroup_id': '2', 'doorgroup_id': '2550'}]
I would further question using getlist, but we would need more deatils from you to deal with that.
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)
I have this example code:
let testData= [{name:'Joshua',age:22,option:"[{value:'test'}]"},{name:'Ali',age:200,option:"[{value:'test2'}]"}]
let parsedData=JSON.parse(testData[0].option);
console.log(parsedData);
Testing my code using this site: https://es6console.com/
It seems that I'm unable to parse & log the data at all.
Any ideas why this is happening?
Your option string is not following the JSON specs: in JSON every key and string value needs to be enclosed in double quotes. So this would work:
let testData= [{
name: 'Joshua',
age: 22,
option: '[{"value": "test"}]'
}, {
name: 'Ali',
age: 200,
option: '[{"value": "test2"}]'
}];
let parsedData = JSON.parse(testData[0].option);
console.log(parsedData);
I think the issue is that JSON object's fields should be wrapped in double-quotes.
E.g.
let testData = [{name:'Joshua',age:22,option:`[{"value":'test'}]`},{name:'Ali',age:200,option:`[{"value":'test2'}]`}]
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 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
});