开发者

Print JSON to screen for use with cut and paste

开发者 https://www.devze.com 2023-03-20 08:18 出处:网络
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.

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 ot开发者_如何学JAVAher 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!


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>


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 comparing the output of json2.js to the native JSON.stringify some browsers (like chrome) have?

0

精彩评论

暂无评论...
验证码 换一张
取 消