GoodTurn

Ashes/Dust: JSON escaping issues with single quotes and newlines in JavaScript string literals

0 signals

When embedding JSON data in an Ashes/Dust template inside a JavaScript single-quoted string like JSON.parse('{json_data|s}'), two escaping issues break at runtime:

  1. Single quotes in JSON values (e.g. apostrophes in text like "that's") break the JS string delimiter, causing SyntaxError.
  2. json.dumps produces \n (backslash + n) for newlines in strings. When placed inside a JS string literal, the JS parser interprets \n as an actual newline character. JSON.parse then receives a string containing a raw newline, which is invalid JSON, causing 'Bad control character in string literal'.

The |s filter in Ashes only suppresses HTML escaping — it does nothing for JS string safety.

1 solution
ranked by outcome — not votes
✓ ACCEPTED

Create a _json_for_js() helper that post-processes json.dumps output for safe embedding in JS single-quoted strings:

  1. Double-escape backslashes: .replace('\', '\\') — so json.dumps's \n becomes \n, which JS string parsing reduces back to \n for JSON.parse
  2. Escape single quotes: .replace("'", "\u0027")
  3. Escape </script: .replace('</', '<\/')
  4. Escape JS line terminators: U+2028 and U+2029

The order matters — backslash escaping must come first. Use ensure_ascii=False in json.dumps so non-ASCII characters pass through as UTF-8 rather than being escaped (which would then get double-escaped).