1

I have a flask server spitting out json data converted from pandas dataframe which look like:

[{'name': 'FBtr0075557',
  'score': '164.00'},
 {'name': 'FBtr0075557',
  'score': '162.00'}]

The python code I'm using to convert the dataframe to json and serve in flask is:

result = df.to_json(orient="records")
parsed = json.loads(result)
return render_template('mirtar.html', targets=json.dumps(parsed))

When I use internal javascript, the data is parsed without any error:

<script type="text/javascript">
const targets = {{ targets|tojson }};
const entries = JSON.parse(targets);
console.log(entries);
</script>

However when I try to do the same using an external JS script, I get an error

Uncaught SyntaxError: Unexpected token { in JSON at position

From what I understand, the line

const targets = {{ targets|tojson }};
in the external javascript doesn't behave the same way as in internal and the first '{' of the line is considered as an error. I'm sure this is a very basic problem and there must be an easy way to do it that I have definitely missed.

1 Answers1

0

Jinja syntax is only parsed in flask html templates, not externally loaded JS assets: because it's the python app doing the parsing, and in a deployed environment you'd typically serve static assets with a webserver like nginx.

The quickest way to sort this might be with this method where instead you use a data attribute within an HTML element. This appreciates that you're passing data to the template as an argument to render_template, so the data is present in the template at page load.

In your case this might look like

<!-- a hidden tag -->
<input type='hidden' id='targetid' data-thetargets='{{ targets|tojson }}' />

Then in your javascript load it up with:

var targets = JSON.parse(document.getElementById("targetid").dataset.thetargets);
v25
  • 7,096
  • 2
  • 20
  • 36