Convert Jinja2 array into JS array

vijay chandamala
2 min readAug 11, 2021

--

It’s so frustrating when you can’t just get over a simple object conversion using stack-overflow or google.

Assuming you’re passing a python dictionary (which is an array of JSON objects) as a template variable while rendering a template ,

You can use the following javascript :

var some_var = '{{ YOUR_ARRAY_TEMPLATE_VARIABLE }}'var your_js_array = Array.from(JSON.parse(some_var))

I know you’ve already tried this and it didn’t work, and you probably saw this error :

jQuery.Deferred exception: Unexpected token o in JSON at position 1 SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
at HTMLDocument.<anonymous>

This happens because your template variable string has (single quotes) instead of (double quotes) while JSON.parse is trying to parse the string.

This can be fixed by a simple find and replace :

var some_var = '{{ YOUR_ARRAY_TEMPLATE_VARIABLE }}'some_var.replaceAll("\'","\"")var your_js_array = Array.from(JSON.parse(some_var))

That should mostly fix your issue, and there are cases it can still fail, one of which could be your JSON string isn’t clean , where there could be ‘ or “ in keys/values or some other escape chars.

That can be fixed as well…

Just try to clean up your JSON string before you render a template from your python(flask) code.

You can identify the chars which are causing issue by copy-pasting your JSON string here : JSON Formatter & Validator (curiousconcept.com)

It’ll tell you what needs to be cleaned up in your JSON string.

That’s it!

Hope this article helped you.

If it did, leave a like or a comment! Have a great day!

--

--

No responses yet