I'm trying to parse a JSON file into a variable, but it would not work for some reason.
If I run the following, it works just fine. I can see the three years printed in the console.
{% block javascripts %}
<script>
var mydates = {
"2018": {
"January": ["week1","week2","week3","week4"],
"February": ["week5","week6","week7"],
"March": ["week8","week9","week11"]
},
"2019": {
"January": ["week1","week2","week3","week4"],
"February": ["week5","week6","week7"],
"March": ["week8","week10","week11"]
},
"2020": {
"January": ["week1","week2","week3","week4"],
"February": ["week5","week6","week7"],
"March": ["week8"]
}
};
for (let year in mydates){
console.log(year)
};
</script>
{% endblock javascripts %}
However, if I run the following, it doesn't work, the console prints 'undefined'. What am I doing wrong?
{% block javascripts %}
{% load static %}
<script>
var mydates;
fetch("{% static 'dates.json' %}")
.then(response => {mydates = response.json()
})
for (let year in mydates){
console.log(year)
};
</script>
{% endblock javascripts %}
dates.json is correctly stored in my static folder and it includes the following:
{
"2018": {
"January": ["week1","week2","week3","week4"],
"February": ["week5","week6","week7"],
"March": ["week8","week9","week10","week11"]
},
"2019": {
"January": ["week1","week2","week3","week4"],
"February": ["week5","week6","week7"],
"March": ["week8","week9","week10","week11"]
},
"2020": {
"January": ["week1","week2","week3","week4"],
"February": ["week5","week6","week7"],
"March": ["week8","week9","week10","week11"]
}
}
Many thanks for your help !