@mapbox/safer-stringify

0.0.2 • Public • Published

#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('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

Dependencies (0)

    Dev Dependencies (1)

    Package Sidebar

    Install

    npm i @mapbox/safer-stringify

    Weekly Downloads

    1

    Version

    0.0.2

    License

    none

    Last publish

    Collaborators

    • mbx-npm-ci-production
    • mbx-npm-ci-staging
    • mbx-npm-advanced-actions-production
    • mbx-npm-advanced-actions-staging
    • mbx-npm-09-production
    • mbx-npm-08-production
    • mbx-npm-07-production
    • mbx-npm-06-production
    • mbx-npm-05-production
    • mbx-npm-04-production
    • mbx-npm-03-production
    • mbx-npm-02-production
    • mbx-npm-01-production
    • mbx-npm-02-staging
    • mapbox-npm-01
    • mapbox-npm-02
    • mapbox-npm-07
    • mapbox-npm-03
    • mapbox-npm-04
    • mapbox-npm-09
    • mapbox-npm-05
    • mapbox-npm-06
    • mapbox-npm-08
    • mapbox-npm-advanced-actions
    • mapbox-npm-ci
    • mapbox-npm
    • mapbox-admin
    • mapbox-machine-user