0

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.

1 Answer 1

1

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" }}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.