4

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!

Chris Dutrow
  • 48,402
  • 65
  • 188
  • 258

3 Answers3

5

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>
Glenn Ferrie
  • 10,290
  • 3
  • 42
  • 73
2

I do the following, its a beautiful hack.

var g = {
    sampleFunc : function (data) {
        var dataAsText = JSON.stringify(data);
        var response = prompt('you can copy and paste this', dataAsText);
    }
}

// usage... 
g.sampleFunc({ id: "4", name: "John Smith" });

JavaScript prompt... gotta love it.

Glenn Ferrie
  • 10,290
  • 3
  • 42
  • 73
1

Are you sure this isn't just a browser rendering thing playing tricks on you? A JSON library is going to escape chars properly to give you a valid JSON string. Have you tried comparing the output of json2.js to the native JSON.stringify some browsers (like chrome) have?

Peter Lyons
  • 142,938
  • 30
  • 279
  • 274
  • It looks like I was incorrect about the source of the problem. The text I was using had html tags in it that were getting rendered, specifically, the

    tag

    – Chris Dutrow Jul 14 '11 at 01:49
  • Glad you figured it out. If you want to display JSON that looks raw (and is valid for copy/paste), you'll want to use or
     tags and escape the HTML entities: < becomes < and so forth. See http://stackoverflow.com/questions/24816/escaping-html-strings-with-jquery for one way to do that.
    – Peter Lyons Jul 14 '11 at 01:58