Passing a JSON object from Django to Javascript doesn't work properly

I need to pass a json object to a javascript script in Django. I used the method described here:

Django: passing JSON from view to template

Here is my view:

 def test_json(request):
    data = {}
    data['key'] = 'value'
    json_data = json.dumps(data)
    return render(request, 'test_json.html', {'json_data':json_data}) 

And my template:

{{ json_data|json_script:"json_data" }}
<script>
  const mydata = JSON.parse(document.getElementById("json_data").textContent);
  const keys = Object.keys(mydata);
  console.log(keys);
</script>

But the console output is this:

[
  "0",
  "1",
  "2",
  "3",
  "4",
  "5",
  "6",
  "7",
  "8",
  "9",
  "10",
  "11",
  "12",
  "13",
  "14",
  "15"
]

It is like it doesn’t recognize the keys but recognize every character of the json object as a key, it is like is not recognizing the JSON structure.

If I change the script in the template like this:

{{ json_data|json_script:"json_data" }}


<script>
   // const mydata = JSON.parse(document.getElementById('json_data').textContent);
//const keys = Object.keys(mydata);
//console.log(keys)
let text = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}'; 

const obj = JSON.parse(text); 
const keys1 = Object.keys(obj);
console.log(keys1)
</script>

Output:

    [
  "employees"
]

I get the key properly. It is like in the process of feeding the JSON from Django to the template the problem.

Any suggestion?

Thanks.

>Solution :

When using the json_script filter there is no need to serialize the object to JSON first, the filter will handle that for you

View

def test_json(request):
    data = {'key': 'value'}
    return render(request, 'test_json.html', {'data': data}) 

Template

{{ data|json_script:"json_data" }}

Leave a Reply