Last Updated: February 25, 2016
·
356
· toumorokoshi

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)