There is an array in the form of JSON, in which I have a Django loop with variables:

var dataJSONArray = JSON.parse('[ {% for client in clients %} {"firstName":"", "lastName":"{{ client.last_name }}", "email":"{{ client.email }}", "phone":"{{ client.phone }}", "company":"{{ client.company }}", "test":"{{ client.demo }}", "joined":"{{ client.date_joined }}", "paidOrder":"{{ client.orders.count }}/{{ client.get_payment_orders.count }}", "launches":"{{ client.get_finished_launches.count }}/{{ client.launched_products.count }}"} {% endfor %} ]'); 

And he, of course, does not want to parse, swears. How can you safely replace Django variables with, say, JavaScript? Thank.

  • one
    in / at least \ formatted \ would \ code \ so that \ it was \ more convenient \ read - Melis

2 answers 2

Corrected:

 console.log(JSON.parse('{"clients":[{% for client in clients %}{"firstName":"","lastName":"{{client.last_name}}","email":"{{client.email}}","phone":"{{client.phone}}","company":"{{client.company}}","test":"{{client.demo}}","joined":"{{client.date_joined}}","paidOrder":"{{client.orders.count}}/{{client.get_payment_orders.count}}","launches":"{{client.get_finished_launches.count}}/{{client.launched_products.count}}"}{% if forloop.last %} {% else %},{% endif %} {% endfor %}]}')); 

I took such an array with python

 clients = [ { "last_name": "Bobov", "email": "mail@gamil.com", "phone": "12", "company": "12", "demo": "12", "date_joined": "12", "orders": {"count": 12}, "get_payment_orders": {"count": 1122}, "get_finished_launches": {"count": 12}, "launched_products": {"count": 252}, }, { "last_name": "B2obov", "email": "mail@gami4l.com", "phone": "1e2", "company": "1r2", "demo": "1t2", "date_joined": "w12", "orders": {"count": 152}, "get_payment_orders": {"count": 13122}, "get_finished_launches": {"count": 212}, "launched_products": {"count": 2552}, }, ] 

    Do not format JSON using templates. Even if everything goes well in testing, the chance that you will receive the most unexpected mistake in the most unexpected place is too great.

    A good way is to select a separate url from which to give json, encoded with standard python tools ( from json import dumps ).