Trying to pass a nested list with JSON to JS with Flask
Question:
The problem is I’m passing my argument to the Javascript like this: link.
The variable "chatlist" is the problem. The value of that variable is
[[{"user": "lol"}, {"msg": "lol has created this chat."}], [{"user": "lol"}, {"msg": "lol"}]]
But when I try to access that variable through this code: link, it ends up looking like
[[{"user": "lol"}, {"msg": "lol has created this chat."}], [{"user": "lol"}, {"msg": "lol"}]]
What I’m expecting is in both my Python code and my Javascript, I get
[[{"user": "lol"}, {"msg": "lol has created this chat."}], [{"user": "lol"}, {"msg": "lol"}]]
as the value of the variable labelled "chatList". This value also needs to be "parsable" (not sure if that’s the right word). I need to be able to access all elements of the list and all keys and values of each dictionary in each element.
Answers:
It looks like the double quotes are getting HTML escaped.
I would solve this by using Javascript’s decodeURI() method.
Pass the list as is to render_template
.
return render_template("chat.html", chatlist=chatInfo, pin=pin)
In the template you can use the jinja filter tojson
.
var chatList = {{ chatlist | tojson }};
console.log(chatList);
The problem is I’m passing my argument to the Javascript like this: link.
The variable "chatlist" is the problem. The value of that variable is
[[{"user": "lol"}, {"msg": "lol has created this chat."}], [{"user": "lol"}, {"msg": "lol"}]]
But when I try to access that variable through this code: link, it ends up looking like
[[{"user": "lol"}, {"msg": "lol has created this chat."}], [{"user": "lol"}, {"msg": "lol"}]]
What I’m expecting is in both my Python code and my Javascript, I get
[[{"user": "lol"}, {"msg": "lol has created this chat."}], [{"user": "lol"}, {"msg": "lol"}]]
as the value of the variable labelled "chatList". This value also needs to be "parsable" (not sure if that’s the right word). I need to be able to access all elements of the list and all keys and values of each dictionary in each element.
It looks like the double quotes are getting HTML escaped.
I would solve this by using Javascript’s decodeURI() method.
Pass the list as is to render_template
.
return render_template("chat.html", chatlist=chatInfo, pin=pin)
In the template you can use the jinja filter tojson
.
var chatList = {{ chatlist | tojson }};
console.log(chatList);