flask to javascript, sending json, running into invalid syntax error - javascript

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.

Related

Flask jinja2 renders new line from database field with errors in javascript

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.

Send JSON from Flask to JavaScript

I have a problem with send data from Flask to JavaScript. I have the informations whitch i get from the database and I add this data to the dictionary. Now I want to have JSON object in JavaScript for dispaly this information on a map. I use JSON.parse in JavaScript but it doesnt work.
Code in route.py
#app.route('/mapaa',methods=['GET','POST'])
def mapa():
slownik = {}
if 'event_form' in request.form:
name = request.form['name_event']
all_data = Event.query.filter_by(name=name).all()
for row in all_data:
slownik.update({'id':row.id})
slownik.update({'date_st':row.date_start})
slownik.update({'date_end':row.date_end})
slownik.update({'type':row.type})
slownik.update({'name':row.name})
slownik.update({'len_route':row.len_route})
slownik.update({'route':row.route})
return render_template('mapaa.html', title='Mapa',data=slownik)
In JavaScript mapa.js:
var parsed = JSON.parse('{{data | tojson}}');
console.log(data)
But it return:
VM475:1 Uncaught SyntaxError: Unexpected token { in JSON at position 1
at JSON.parse (<anonymous>)
What I am doing wrong ? I will add that date_end and date_start are datatime type. I tried to jsonify this dictionary too but it also doesnt work.
You can use this within your template mappa.html scripttag to parse thejson using [tojson`](https://jinja.palletsprojects.com/en/2.10.x/templates/#tojson) filter:
<script>
var parsed = {{ data | tojson | safe}};
console.log(parsed)
</script>

How to render json data with # character in its key using handlebars?

This is my json data
var data = {john#gmail.com: true}
In my template i am trying this way to display data but its not working
{{data.[john#gmail.com]}}
I even tried this way
{{data.['john#gmail.com']}}
and also
{{data.john#gmail.com}}
but if i had changed my json data to
var data = {john:true}
and try
{{data.[john]}}
its working and displaying the output as true
Can anyone please point me where i am making mistake ?
It is like this data["john#gmail.com"]. Here is a good Resource to read

How to access a json object in javascript files from a model passed to the view

I have a JSON object in my database that contains html inside it. I pass the object as part of a model to my view. I need to access the object and read it in the javascript files for the page. However when i try and assign the object to a global variable in my html file i cannot access it in my javascript file.
I tried reading the object as a string it returns decoded html (
"page-1":) which i cant do anything with. If i call #Html.Raw(#Model.CourseContent.ExpectedResult) it created the JSON object as expected. However in my javascript file it is listed as undefined. I have no idea how to solve this.
#model DataTransferObjects.Models.UserCourseAndContent
<script>
var totalPages = '#Model.CourseContent.TotalPages';
var expectedResults = #HTML.Raw(#Model.CourseContent.ExpectedResult)
</script>
The json object that comes out when i use the above code looks like
var expectedResults = {
"page-1": "<head></head><body></body>",
"page-3": "<head></head><body><h1>My Cool News Article</h1><p>Welcome
to my news article, you’ll find some cool news here.</p>
<Our most recent
news</<p>Below you’ll find my most recent news!</p></body>"
};
I expected it to be an actual json string but instead ive got an object (?) i am confused as to how to decode the html out of it then turn the resulting json obejct into a json string to be read in the javascript file.
Any help would be great!
var expectedResults = {
"page-1": "<head></head><body></body>",
"page-3": "<head></head><body><h1>My Cool News Article</h1><p>Welcome
to my news article, you’ll find some cool news here.</p>
<Our most recent
news</<p>Below you’ll find my most recent news!</p></body>"
};
// Parse JSON
const parsedJSON = JSON.parse(JSON.stringify(expectedResults));
// Access to properties
const page-1 = parsedJSON['page-1'];
const page-3 = parsedJSON['page-3'];

Send json to jade

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

Categories

Resources