Search code examples
javascriptjsonescapingstringify

Print JSON to screen for use with cut and paste


This is going to sound really ghetto, but I need to print some Javascript to the browser screen so that it can be cut and pasted into another program.

I'm using JSON.stringify() from json2.js, however, its not escaping characters such as quotes and new lines (",\n) which are actually control parts of a JSON object and need to be escaped.

For example, I'd get strings like this that cause problems when importing into the other program:

{
    string_property_01 : "He said "HI"";  // The string terminates after "He said "
}

Are there any libraries that I can use to escape all the characters that I need to escape here?

Thanks!


Solution

  • Option #2

    var g = {
        sampleFunc2 : function (data) {
            var dataAsText = JSON.stringify(data);
            // w jquery
            $('#debugArea').text(dataAsText);
        }
    }
    
    // usage... 
    g.sampleFunc2({ id: "4", name: "John Smith" });
    

    In markup:

    <textarea id='debugArea' rows='10' cols='50'></textarea>