6

I have a python code which converts the normal dict into JSON as follows

groups = {
    'g_1': [
        {'name': 'something', 'id': '1'}, 
        {'name': 'something', 'id': '1'}
    ], 
    'g_2': [
        {'name': 'something', 'id': '1'}, 
        {'name': 'something', 'id': '1'}
    ]
}

I have used json.dumps to convert that to a json as follows

import json
groups = json.dumps(groups)

I want to read the data in javascript as an object. How to I access it?

I tried var groups=JSON.parse({{ groups }}) it didn't work out. Help me in parsing the data as javascript object.

  • 2
    Did any of the following answers, satisfied you? If so, please accept one. Its a good practice in StackOverflow. – nik_m Mar 08 '17 at 21:48

4 Answers4

9

This should work:

var groups = JSON.parse('{{ groups|safe }}');

nik_m
  • 11,825
  • 4
  • 43
  • 57
0

try:

var groups = JSON && JSON.parse({{ groups }})|| $.parseJSON({{ groups }});
alfredo138923
  • 1,509
  • 1
  • 15
  • 15
  • Still wont work for me. The code would print out something like $.parseJSON({'key': 0}) . And raise Uncaught SyntaxError: Unexpected token & – Marcelo Fonseca Mar 14 '19 at 13:59
0

You may have troubles with ' character trying to run var groups = "{{ groups|safe }}"; or var groups = '{{ groups|safe }}';. If both answers don't work try this solution:

function escapeRegExp(str) {
    return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
function replaceAll(str, find, replace) {
    return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}

var str = "{{ groups|safe }}";
var new_str = replaceAll(str, "'", "\"");

var groups = JSON.parse(new_str);

I had to replace all ' to " in the dictionary for JSON.parse to work. To know more about these functions check Stack How to replace all occurrences of a string in JavaScript question.

Marcelo Fonseca
  • 1,705
  • 2
  • 19
  • 38
0

For others looking for this,

In view:

import json
from django.core.serializers.json import DjangoJSONEncoder

...
groups = {
'g_1': [
    {'name': 'something', 'id': '1'}, 
    {'name': 'something', 'id': '1'}
], 
'g_2': [
    {'name': 'something', 'id': '1'}, 
    {'name': 'something', 'id': '1'}
]
}
...
return render(request=request,
          template_name=self.template_name,
          context={'groups' : json.dumps(groups, cls=DjangoJSONEncoder),})

In Template:

var groups = {{groups|safe}};

Info on DjangoJSONEncoder

Jeff K
  • 230
  • 3
  • 6