I'm trying to work with some JSON data into my JavaScript using JSON.parse in my Flask app. However, I'm getting the following error.
Uncaught SyntaxError: Unexpected token m in JSON at position 3
I'm suspecting it may be something to do with the quotes, but am not sure. Code is below.
Python (app.y)
import pandas as pd
from flask import Flask, render_template
import json
test_data = [['mack', 10, 988], ['john', 15, 200], ['jane', 14, 590]]
test_df = pd.DataFrame(test_data, columns=['Name', 'Age', 'Score'])
json_df = test_df.set_index('Name').to_json(orient='index')
@app.route("/hello")
def index():
return render_template("index.html", json_df=json_df)
JavaScript (within my index.html file)
<script>
const json_df = JSON.parse('{{ json_df|tojson }}');
console.log(json_df);
</script>
Basically, I want to be able to work with the data in JavaScript, such that:
const json_df = {mack:{Age:10,Score:988},john:{Age:15,Score:200},jane:{Age:14,Score:590}}
json_dfalso already is JSON. Just doconst df = {{ json_df }};.json_dfis a string like'{"mack": ...}'. When you put this into a template withconst df = {{ json_df }};, the result will beconst df = {"mack": ...};. This is now already a fully valid Javascript object.var json_df = '...';, then it's a string and not an object. If your JS code looks likevar df = {...};, then it's an object.