Skip to content

Instantly share code, notes, and snippets.

@RandomEtc
Created May 11, 2012 05:18
Show Gist options
  • Select an option

  • Save RandomEtc/2657669 to your computer and use it in GitHub Desktop.

Select an option

Save RandomEtc/2657669 to your computer and use it in GitHub Desktop.

Revisions

  1. RandomEtc created this gist May 11, 2012.
    26 changes: 26 additions & 0 deletions escaped-json.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    // preserve Twitter's style of JSON string encoding...
    // escape higher value unicode (lowercase hex)
    // escape < and > (uppercase hex)
    // escape / in strings (\/)
    // hugs! https://gist.github.com/1306986
    // http://stackoverflow.com/questions/4901133/json-and-escaping-characters
    function escapedStringify(s, emit_unicode) {
    var json = JSON.stringify(s);
    return emit_unicode ? json : json.replace(/\//g,
    function(c) {
    return '\\/';
    }
    ).replace(/[\u003c\u003e]/g,
    function(c) {
    return '\\u'+('0000'+c.charCodeAt(0).toString(16)).slice(-4).toUpperCase();
    }
    ).replace(/[\u007f-\uffff]/g,
    function(c) {
    return '\\u'+('0000'+c.charCodeAt(0).toString(16)).slice(-4);
    }
    );
    }

    module.exports = {
    stringify: escapedStringify
    };