最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Print JSON to screen for use with cut and paste - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 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>

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?

发布评论

评论列表(0)

  1. 暂无评论