I have an array of JSON data that I want to pass from a Flask template to HTML to a static JS script for a d3.js visualization. Based on this post, I had set it up as follows:
In Flask (routes.py):
@app.route('/demo_statements')
def demo_statements():
return render_template('tp_demo_statements.html', title='Statements Demo', data=
[{
"tp_utt_a": "77",
"tp_utt_c": "28",
"tp_utt": "105",
"tp_uttlen_a": "3.6",
"tp_uttlen_c": "1.6",
"tp_utt_metric": "2.0",
"tp_utt_a_s": "78",
"tp_utt_c_s": "25",
"tp_utt_s": "103",
"tp_uttlen_a_s": "3.7",
"tp_uttlen_c_s": "1.9",
"tp_utt_metric_s": "2.0",
}]
)
In HTML (tp_demo_statements.html):
<div class="col-12" id="statements" data_dict='{{ data | tojson }}'>
and the script:
<script type="text/javascript" src="{{ url_for('static', filename='js/statements.js') }}"></script>
In JS (statements.js):
var data_dict = JSON.parse(document.getElementById("statements").dataset.data_dict);
However, this is returning Uncaught SyntaxError: Unexpected token u in JSON at position 0 in the console.
My intuition is that the problem is happening between the HTML and the JS (i.e. the data is not getting passed into the JS properly). When the data is entered directly into the JavaScript file, the visualization loads as expected, so it's definitely not a problem further downstream. I've tried other permuations to define the data, such as:
var data_dict = document.getElementById("statements").dataset.data_dict;
var data_dict = JSON.parse($("#statements").data("data_dict"));
var data_dict = $("#statements").data("data_dict");
None of these work! What am I doing wrong? Any assistance would be much appreciated!