Dumping objects to Javascript in templates with any language
Have you ever had a situation where you needed to dump a javascript object onto a template? Dealing with pesky issues like escaping characters and proper formatting? Here's a nice fix (I'm using python since I'm most familiar)
import json # get a json parser
# build your object in your language of choice
my_object = {
"foo": "this is an argument",
"bar": "this is a crazy string\nwith newlinse and a$^(()@()"
}
# if you dump it with json, you get a perfectly formed javascript object
# escapes and all.
my_object_javascript = json.dumps(my_object)
Written by Yusuke Tsutsumi
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Python
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#