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!
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!
Share Improve this question asked Jul 14, 2011 at 1:08 Chris DutrowChris Dutrow 50.5k67 gold badges196 silver badges262 bronze badges 1- How do you print it to the screen? – Dr.Molle Commented Jul 14, 2011 at 1:31
3 Answers
Reset to default 5Option #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>
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.
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 paring the output of json2.js to the native JSON.stringify some browsers (like chrome) have?