I am sending a big json file from server to jade, but the " are replaced with: " therefor the json is unreadable/unparsable and I get this error:
Uncaught SyntaxError: Unexpected token &
I send the data like this from node:
res.render(view, {world:{name:"SomeName",width:50},otherdata:{...}});
and then get it in jade like this:
doStuff(JSON.parse(#{data}));
and here it is unreadable data which looks like:
{world:{name:"SomeName",width:50...
can I somehow disable the conversion of the quotes?
Server side within your rout you will do the following consider the object user
var user = {username:"myname"};
res.locals.user = user ;
response will be :
res.render('view');
jade view will have the variable available :
if user
script(type='text/javascript').
var user = !{JSON.stringify(user)};
Try adding app.use(bodyParser.json()); if you still have the issue
hope that helps
No experience with jade but from the language reference (http://jade-lang.com/reference/interpolation/) i guess
doStuff(JSON.parse(!{data}))
might work
Related
I am saving data in Flask application from a textarea.
After saving it I am trying to receive it back to html via javascript like this:
const item = "{{item}}";
It gives me the following error:
Uncaught SyntaxError: Invalid or unexpected token
On server side I am just retuning lik this:
item = Item.query.filter_by(id=id).first()
item=item.body
Error appears only when i save via textarea with a new line.
How can I fix this?
So far I tried: this works only if I change from '' and "" to template literals ``:
const item = `{{item}}`;
But I am not sure if this method is safe since it makes auto escaping. From jinja2 documentation: "String literals in templates with automatic escaping are considered unsafe because native Python strings are not safe."
Also const item = "{{item | safe}}"; seems not helping.
I ran into this error while trying to send a pandas to_json object to front end using flask. the codes and errors look like this:
df_higg_msi_scored_manual = pd.read_csv(r'static/CSVFiles/higg_msi_scored_manual.csv')
materials = df_higg_msi_scored_manual.iloc[:33, 3]
material = materials.to_json(orient="values")
return render_template('/impacttool.html', material = material)
var user = JSON.parse('{{brand | tojson | safe}}');
and this is the error that pops up no matter how valid the resulting json file is:
depending on which json i send to the front end, i get either unexpected number or unexpected token, with unexpected token always matching the first alphabet of the first string in json. Could someone please help me figure this out? I've even tried print(material) on flask, then copied the exact json that was printed to the console, assigned that to a variable and sent it to the front end and it worked fine! but for some reason when i do to_json and assign it directly to a variable it throws this error. If someone knows how to fix it I would love to know. Thank you.
In your Javascript try to see what
console.log('{{brand | tojson | safe}}')
gets you because maybe you're trying to turn JSON data into JSON data so maybe also consider removing the | to json part of the variable call
Edit: calling variables doesn't work in files other than HTML files so try parsing the variable directly in the HTML file like so:
<script>
var user = JSON.parse('{{brand | tojson | safe}}')
</script>
or you could add it to a variable in the HTML file then parse it in the javascript file like so:
filename.html:
<script>
var jsondata = '{{brand | tojson | safe}}'
</script>
filename.js
var user = JSON.parse(jsondata)
I found a solution thanks to RaphSinai, it was because the {{ brands | tojson }} was formatted with extra double quotes as "[whatever...]" instead of just the [], so I changed the code from material = materials.to_json(orient="values") to json.loads(material = materials.to_json(orient="values")) and it worked fine.
I have an app running in Node.js with Express, and I wanted to dinamically change options on select object with jquery. This is actually not a big problem, but I'm having troubles on using the res.render parameters (which are mongoose documents) in the script tag. I use them without any trouble on the html (jade actually), but in the script tag I get a problem with the ObjectId not being a String.
This is an extract of the code:
On the backend:
router.get("/new", function(req, res){
res.render("session/documentos/new",
{
services: res.locals.services
});
});
On the view
block content
div
h1(class="text-center") New document
form(id="newDoc" action="/session/documentos" method="POST")
div(class="tab") Service:
div(class="form-group")
select(class="form-control" name="svc" id="svc")
option(value="undefined" disabled selected) Choose one
for service in services
option(value=service._id)=service.name
script.
$(document).ready(function() {
var sessLenght = 0;
var selectedSvc = #{services};
$("#svc").change(function(){
console.log("Service changed: " + selectedSvc);
});
});
And this is the error I'm getting:
Console error
And in Sources:
Source error on ObjectId
So I'm being able to use with no troubles the "services" collection of documents, but when trying to use them on the script tag I'm getting problems with the ObjectId element.
I was thinking that one soution would be to convert to string the ObjectId when querying the database, but I think there might be a cleaner solution to that. Which might be the best way to solve the issue?
Any thoughts appreciated! Thanks in advance
Try to change var selectedSvc = #{services};
to var selectedSvc = !{services};
or var selectedSvc = !{JSON.stringify(services)};
I have my NODE-RED schemma:
following string result from my "Function" node my node:
msg.payload : string[63]
"{"random":{"date":"22:55","random":21},"time":{"time":"22:52"}}"
This is the code of my "Function Node":
msg.payload.random=context.global.randomandtime;
msg.payload.time=context.global.time;
return msg;
I need to put in "part of the string" (not all) like this =>{"date":"22:55","random":21} and show it in my browser like a webpage but not using html tags.
Like this:
22:55
21
Any help will be wellcome.
I have added template(Mustache) and I am traying to bring data to it,(Note:http response is already in schemme but not shown here)
I am traying to bring data here (template). But I get error.
The Mustache template body is:
This is the payload: {{#payload.randomandandtime.random}} !
But I have back this error back:
2017-5-18 16:18:00node: Mustachemsg : string[56]
"Unclosed section "payload.randomandandtime.random" at 59"
In browser I get
502 Bad Gateway: Registered endpoint failed to handle the request.
Even If I change it only payload.randomandandtime I get empty:
payload.randomandandtime
In browser & console:
Messsage received back: (empty)
This is the payload: !
Finally I solved in this way.
I make all in one Global varaible instead 2 global variables.
I passed it to mustache template and in Mustache I worked with context in order to get it.
General Scheme:
Then in recoverydata:
msg.payload = context.global.get("randomtime");
In My Mustache:
`{{#payload.random}}
Last random number request returned {{&payload.random}}, which was received
at {{&payload.randomtime.times}}{{/payload.random}}
{{/payload}}`
The resul of it is a Webservice not using HTML and this is:
url https://....../page
"Time last server time request received at 13:14 Last random number request returned 94, which was received at 13:14"
I'm trying to pass an object from my endpoint to Jade but It keeps giving me Uncaught SyntaxError: Unexpected identifier on Stat! Can someone help me please. Here is my code:
app.get('/stats', function (req, res, next) {
var stats ={
'm0t20': {a:0,b:0,c:0,d:0},
'm20t30': {a:0,b:0,c:0,d:0},
};
res.render('chart',{'stat':stats});
}
and in my jade and I cant get the value of stat:
script(type='text/javascript').
var stats= #{stat};
If you want to interpolate object from you express, the easiest and cleanest way is to serialize them.
For the moment, once interpolated, you are trying to write something like this:
var stats = [Object object];
Which isn't a valid JavaScript syntax :/
So, on the server side, serialize your object:
app.get(..., function (req, res) {
var stats = { ... };
res.render('chart', { stats: JSON.stringify(stats) });
});
And, on the client side, just use the serialized object; You'll need to use ! instead of # to prevent jade from escaping characters like quotes.
script.
var stats = !{stats};
alert(stats.myProp);
Keep in mind that you are injecting direct JavaScript code into your page.
DO NOT do that if the serialized object could contain any user input