Skip to content
This repository has been archived by the owner on Jul 13, 2023. It is now read-only.
/ safer-stringify Public archive

A stringify template helper for outputting JSON with escaped forward slashes and line terminators.

Notifications You must be signed in to change notification settings

mapbox/safer-stringify

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

#safer-stringify

Like JSON.stringify, but escapes forward slashes and line terminators.

Build Status

NPM

##Usage Same arguments as JSON.stringify:

saferstringify(obj, replacer, spaces)

var saferstringify = require('@mapbox/safer-stringify');

var obj = {};
obj.github = 'http://www.github.com/mapbox/saferstringify';
obj.escape = 'ro
cks'; // has hidden \u2028 literal between `ro` and `cks`
obj.script = '<script>wut("lol")</script>';

saferstringify(obj, null, 2);

Output:

{
  "github": "http:\/\/www.github.com\/mapbox\/saferstringify",
  "escape": "ro\u2028cks",
  "script": "<script>wut(\"lol\")<\/script>"
}

##Why?

A unescaped </script> tag in JSON will be parsed in HTML as the closing script tag regardless of whether it was intended as that or not. See http://stackoverflow.com/questions/66837/when-is-a-cdata-section-necessary-within-a-script-tag/1450633#1450633

u2028 and u2029 must be escaped because no string in JavaScript can contain a literal U+2028 or a U+2029, as they are line terminators. See http://timelessrepo.com/json-isnt-a-javascript-subset

##Tests

npm test

About

A stringify template helper for outputting JSON with escaped forward slashes and line terminators.

Resources

Code of conduct

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 3

  •  
  •  
  •