I am working in Django, where I am sending a Python Dictionary into an HTML file.
In that HTML File, I want to access the Python dictionary and append the keys and values of dictionary into the Javascript arrays. I am able to access Python dictionary in HTML, but can't do the same in Javascript.
This is how I am able to access the values of Dictionary in HTML,
{% for key, image in predictedLabel.items %}
<tr>
<th scope="row">{{ key }}</th>
<td>{{ image }}</td>
</tr>
{%endfor%}
The Javascript script that I have is of Pie Chart, which is as given below,
<script>
var xArray = [];
var yArray = [];
var xArray = ["Italy", "France", "Spain", "USA", "Argentina"];
var yArray = [55, 49, 44, 24, 15];
var layout = { title: "Distribution of Labels" };
var data = [{ labels: xArray, values: yArray, hole: .5, type: "pie" }];
Plotly.newPlot("myPlot", data, layout);
</script>
I want to put the Python Dictionary Key into the xArray and the Values of Dictionary into the yArray. For that, I need to access the Python Dictionary in the Javascript script, but I do not know how to access the Python values in the Javascript script. Can anyone help me in this regard?
You can pass the dictionary in JSON form to the client. This is commonly done like this:
import json
# ... send to client
json = json.dumps(dict_name)
Then in your template:
<script type="application/json">{{ json }}</script>
Then in your JavaScript you can simply do:
const data = JSON.parse(document.querySelector('script[type="application/json"]'));
// do something with 'data'