views:

205

answers:

2

Hello,

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: http://stackoverflow.com/questions/168214/pass-a-php-string-to-a-javascript-variable-including-escaping-newlines BUT how do I do that in Python/Django?

+1  A: 

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>
adamk
I get an error after this line: 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?
wenbert
Could it be that you added to your template `var geodata = "{{ geodata }}";`? It should be without the quotes.
adamk
Nope. I have tried that without the quotes. I get a "Uncaught SyntaxError: Unexpected token , [10.353527, 123.91352500000001]]];\n" in Firefox
wenbert
you must have autoescaping on... try to put in your template `{{ geodata|safe }}` (also fixed in the answer)
adamk
A: 

Okay, I solved my problem and would like to answer my own question. I figured it would be better for the other users here.

First, get the file here: http://www.JSON.org/json_parse.js

var geodata = json_parse("{{geodata|escapejs}}");

I just used escapejs: http://docs.djangoproject.com/en/dev/ref/templates/builtins/#escapejs

EDIT: Thanks to Ignacio Vazquez-Abrams. It was him that helped me in #python Freenode. Should have credited him when I made this post. I didn't know he was in Stackoverflow.

wenbert
Oh did you then.
Ignacio Vazquez-Abrams
Seriously thanks ;) I didn't know you were in Stackoverflow
wenbert