Python - How to export JSON in JS - javascript

I want to export a JSON string in python into a JS variable.
<script type="text/javascript">
var data = JSON.parse('{{ dataJSON }}');
console.log(data)
</script>
If I print the content of dataJSON I get: [{"offset":0,"total":1,"units":[{"village_id":37,"village_name":"Glim
But in the JS I get this: JSON.parse('[{"offset":0,"total":1,"units":[{"village_id":37
I use jinja2 template engine: http://jinja.pocoo.org/docs/dev/templates/#if
How can I fix that?

You need to mark the data as safe:
var data = {{ dataJSON|safe }};
This prevents it from being HTML-escaped. There is no need to use JSON.parse() this way; JSON is a valid JavaScript subset (at least insofar that the Python json module produces a valid subset).
Take into account that this doesn't make it JavaScript safe. You may want to adjust your JSON serialisation. If you are using Flask, a tojson filter is provided that ensures you get JavaScript-safe valid JSON:
var data = {{ data|tojson|safe }};
If you are not using Flask, post-process the JSON:
dataJSON = (json.dumps(data)
.replace(u'<', u'\\u003c')
.replace(u'>', u'\\u003e')
.replace(u'&', u'\\u0026')
.replace(u"'", u'\\u0027'))
This is Python code to produce a dataJSON value that can be safely used in HTML (including attribute values) and in JavaScript. Credit here goes to the Flask json.htmlsafe_dumps() function.

Related

how to access the data sent from server(using flask), in javascript code?

from my server I sent a data like this to my front end,
return render_template("home.html", username=username)
I can access this data in the HTML using {{ username }}
But if I want to use this in javascript code(in script tags) how would I do that?
In order to use the data fetched from a Flask server in script tags, you have to convert the object into JSON representation which you can easily do by using Flask's tojson() template filter. For more info about tojson() visit this link.
Solution to your problem -
<script>
var username = JSON.parse('{{ username | tojson | safe}}');
//you can now use it in whichever way you want to
</script>
Hope this works for you.

Django - JSON file to DTL and JavaScript

I am trying to read a JSON file and pass its content to my template like this:
with open('Directory_To_Json', "r") as data:
content = json.load(data)
return render(request, 'Displayer/index.html', {'Content': content})
It works, but I also want to be able to work with the same JSON inside of my javascript. I tried it like this:
var jsonData = JSON.parse("{{Content}}");
But there is an error at the second position, although the JSON itself is valid. (I tried adding the "safe" modifier as well)
I guess it's because I pass it the json.load output, which is formated to work with Python. But how can I pass it the raw json file content?
Thanks in Advance
json.load() returns a dictionary. You can convert a dictionary to a JSON string using json.dumps()
Try this:
with open('Directory_To_Json', "r") as data:
myjson = json.load(data)
content = json.dumps(myjson)
return render(request, 'Displayer/index.html', {'Content': content})

Can't pass json from html to javascript in Flask? [duplicate]

I want to export a JSON string in python into a JS variable.
<script type="text/javascript">
var data = JSON.parse('{{ dataJSON }}');
console.log(data)
</script>
If I print the content of dataJSON I get: [{"offset":0,"total":1,"units":[{"village_id":37,"village_name":"Glim
But in the JS I get this: JSON.parse('[{"offset":0,"total":1,"units":[{"village_id":37
I use jinja2 template engine: http://jinja.pocoo.org/docs/dev/templates/#if
How can I fix that?
You need to mark the data as safe:
var data = {{ dataJSON|safe }};
This prevents it from being HTML-escaped. There is no need to use JSON.parse() this way; JSON is a valid JavaScript subset (at least insofar that the Python json module produces a valid subset).
Take into account that this doesn't make it JavaScript safe. You may want to adjust your JSON serialisation. If you are using Flask, a tojson filter is provided that ensures you get JavaScript-safe valid JSON:
var data = {{ data|tojson|safe }};
If you are not using Flask, post-process the JSON:
dataJSON = (json.dumps(data)
.replace(u'<', u'\\u003c')
.replace(u'>', u'\\u003e')
.replace(u'&', u'\\u0026')
.replace(u"'", u'\\u0027'))
This is Python code to produce a dataJSON value that can be safely used in HTML (including attribute values) and in JavaScript. Credit here goes to the Flask json.htmlsafe_dumps() function.

Pass JavaScript variable to Flask url_for

I have an endpoint that takes a value in the url and produces some content that will be inserted into a div. I want to build the url with url_for using a JavaScript variable. However, $variable1 is passed as a string, rather than the value of variable1. How can I pass the value of a JavaScript variable to url_for?
function myFunction() {
var variable1 = "someString"
$('#demo').load(
"{{ url_for('addshare2', share = '$variable1') }}"
);
}
Sometimes I use the following workaround with a temporary placeholder string:
var variable1 = "someString";
$('#demo').load(
"{{ url_for('addshare2', share='ADDSHARE2') }}".replace("ADDSHARE2", variable1)
);
It doesn't feel quite right and I'm still looking for a better solution. But it does the job.
You can't evaluate JavaScript in Jinja. You're trying to generate a url on the server side while Jinja is rendering, but you're referencing a variable that is only available in the JavaScript running on the client browser.
Building the url on the client side is the most straightforward fix. (I don't know what your route looks like, so here's an example.)
$('#demo').load('/url/for/addshare2/' + variable1);
However, this isn't very useful because you can't use url_for, so you have to hard-code the urls. This is a good sign that what you want is an AJAX endpoint that you pass parameters to, rather than an endpoint that contains values.
#app.route('/addshare2', methods=['POST'])
def addshare2():
share = request.json['share']
...
return jsonify(result=...)
Now you can generate the url with url_for, and pass the parameters as form data.
$.post(
'{{ url_for('addshare2') }}',
{share: variable1},
function (data) {
// do something with data on successful response
}
);
It's possible to send a variable in Jinja by making a template filter to unquote the text returned by url_for()
add this to your app.py:
from urllib.parse import unquote as urllib_unquote
#app.template_filter('unquote')
def unquote(url):
safe = app.jinja_env.filters['safe']
return safe(urllib_unquote(url))
then on template do:
function myFunction() {
var variable1 = "someString"
$('#demo').load(
`{{ url_for('addshare2', share = '${variable1}')|unquote }}`
);
}
this will do the trick.
More on custom template filters: https://flask.palletsprojects.com/en/2.1.x/templating/#registering-filters

How to pass data from python to javascript in web2py

I see some relevant posts to my query.
Tornado is used in the below link
How to pass variable from python to javascript
I know that it can be done using json but I am not clear how to implement it.
In the web2py default controller I am returning a dictionary which contains the latitudes and longitudes.
def index():
lat_long_list=[]
info1 = {'lat':'1.0032','long':'2.00003','name':'Akash'}
info2 = {'lat':'1.2312','long':'-1.0034','name':'Kalyan'}
lat_long_list.append(info1)
lat_long_list.append(info2)
return dict(lat_long_list=lat_long_list)
In java script I want to iterate through the list of dictionaries and mark the points on the google maps.
I cannot say
<script>
{{ for lat_long_rec in lat_long_list :}}
var name = {{=lat_long_rec['name']}}
{{ pass }}
</script>
This fails. An alternative to handle this is to write the list into an xml and from javascript read the file but I dont want to achieve it this way as writing to file is non performant. Let me know how best this can achieved.
Convert the Python list to JSON and pass that to the view to insert in the Javascript code:
from gluon.serializers import json
return dict(lat_long_list=json(lat_long_list))
In the view:
<script>
...
var latLongList = {{=XML(lat_long_list)}}
...
</script>

Categories