Template string escaping fixes

Fixes #1209.
so I would do a check if JSON is defined, and use it to escape, and fallback to escapestring otherwise. other than that the change looks good to me.