Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Parse JSON in my template using Javascript

I have this in my view:

string_location = myaddress2     geodata = []     for place, (lat, lng) in g.geocode(string_location,exactly_one=False):         geodata.append((place, (lat, lng)))      geodata_results = len(geodata)      data = {"geodata": geodata, "geodata_results":geodata_results }     return render_to_response("business/business_view.html",                               data, context_instance=RequestContext(request)) 

How would I "handle" / convert geodata into JSON and pass it to my template so that I can "loop" through it like an array?

Am I right to think that I can do it this way? If not, then please suggest on a better solution.

Thanks!

UPDATE

var geodata = "[["M. L. Quezon Street<br/>Mandaue City, Philippines", [10.351381999999999, 123.923535]], ["Talamban<br/>Cebu City, Philippines", [10.353527, 123.91352500000001]]]";  

I think the JSON is not escaped? How do I escape special characters inside the json string? I keep getting a newline error.

For PHP, I would json_encode() to fix this. Like in this post: Pass a PHP string to a JavaScript variable (and escape newlines) BUT how do I do that in Python/Django?

like image 916
wenbert Avatar asked Jul 27 '10 15:07

wenbert


People also ask

Can I use JavaScript in Django template?

Adding JavaScript to Our Django TemplateWe can add JavaScript to our template using an inline <script> tag or an external JavaScript file. Let's create a app. js file, put it in a js folder that you need to create in the static folder of your application.

Is JSON Parsable JavaScript?

JSON.parse() A common use of JSON is to exchange data to/from a web server. When receiving data from a web server, the data is always a string. Parse the data with JSON.parse() , and the data becomes a JavaScript object.

What is parse JSON in JavaScript?

JSON parsing is the process of converting a JSON object in text format to a Javascript object that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON. parse() , as the Javascript standard specifies.

How do I parse JSON in Powerautomate?

Using 'parse JSON' action Instead of select operator, if you want to get multiple values from JSON like more than 3 or 4 then we can achieve it using 'Parse JSON' which is a standard connector. Configure parse JSON accordingly. The value of content will be the 'body' value from 'Send an HTTP request to SharePoint.


1 Answers

You could use the built-in json module:

>>> import json >>> geodata = [ ( "Here", (1003,3004) ), ("There", (1.2,1.3)) ] >>> json.dumps(geodata) '[["Here", [1003, 3004]], ["There", [1.2, 1.3]]]' 

You can then simply embed the resulting string inside a javascript script:

<script type='text/javascript'> var geodata = {{ geodata|safe }}; </script> 
like image 94
adamk Avatar answered Oct 01 '22 02:10

adamk