0

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}}
7
  • 1
    you should use dict instead of json. or first load index page then call json from another route. Commented Jun 30, 2022 at 7:06
  • 1
    You don't need to parse the JSON. JSON is literally valid Javascript. You don't need to package it in a string that needs to be parsed. json_df also already is JSON. Just do const df = {{ json_df }};. Commented Jun 30, 2022 at 7:16
  • @deceze when you take the JSON directly without parsing, it remains in this notation, and I can't pull directly by the key (e.g., with json_df.mack) Commented Jun 30, 2022 at 8:36
  • 1
    Your Python json_df is a string like '{"mack": ...}'. When you put this into a template with const df = {{ json_df }};, the result will be const df = {"mack": ...};. This is now already a fully valid Javascript object. Commented Jun 30, 2022 at 8:40
  • 1
    If your JS code looks like var json_df = '...';, then it's a string and not an object. If your JS code looks like var df = {...};, then it's an object. Commented Jun 30, 2022 at 8:58

0

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.