1

I use this template to pass values from Flask to the frontend (chart)

@app.route("/allusers", methods=["POST", "GET"])
def allusers():
    if request.method == "GET":
        user_collection = mongo.db.users
        df = pd.DataFrame(list(user_collection.find()))
        df["price"] = df["price"].apply(pd.to_numeric)
        result = round(df["price"].mean(), 2)
        return render_template(
            "/result.html",
            result=result,
            nrow=df.shape[0],
            series=list(df["price"]),
            description=list(df["description"]),
        )

The price values give work perfectly fine, but the strings which I console.log

{{description}} 

in the HTML gives me this:

['dfsf', 'dfsfggg', 'dfsf', 'dfsdfs']

console.log("{{description}}");

This gives me:

['dfsf', 'dfsfggg', 'dfsf', 'dfsdfs']

I have to use it in JS like this:

  <script>
    $(function() {
      console.log("{{description}}");

      $("#container").highcharts({
        chart: {
          animation: {
            duration: 1000
          }
        },

        xAxis: {
          categories: ["Bla", "bla2", "bla3", "Bla4"]
        },

        series: [
          {
            data: JSON.parse("{{series}}"),
            name: "Price"
          }
        ]
      });
    });
  </script>

The strings seem to get converted somehow. Can anyone tell me what happens there and what I can do about it?

5
  • Possible duplicate of Unexpected token { in JSON while passing data from flask to javascript Commented Nov 17, 2019 at 10:45
  • that comes closer, but it does still not work: JSON.parse("["dfsf", "dfsfggg", "dfsf", "dfsdfs"]"); is the result Commented Nov 17, 2019 at 10:49
  • JSON will always use double quotes, try enclosing the string using single quotes to avoid requiring the need to escape those double quotes, i.e. JSON.parse('{{ series | tojson }}'), like how it is in the answer linked. Commented Nov 17, 2019 at 10:51
  • thank you,... i did not see this, my "prettier" extension recodes single quotes to double quotes >_< Commented Nov 17, 2019 at 10:54
  • +1 for keeping the site tidy. Commented Dec 9, 2019 at 10:45

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.