将JS对象转换为JSON字符串

如果我用JS定义了一个对象:

var j={"name":"binchen"};

我如何将对象转换为JSON? 输出字符串应该是:

'{"name":"binchen"}'

目前所有的浏览器都内置了原生的JSON支持。因此,只要你不处理像IE6 / 7这样的史前浏览器,你就可以像这样简单地做到这一点:

var j={"name":"binchen"};
JSON.stringify(j); // '{"name":"binchen"}'

使用JSON.stringify()或大多数现代浏览器中的本机。

   JSON.stringify(value, replacer, space)
        value       any JavaScript value, usually an object or array.

       replacer    an optional parameter that determines how object
                    values are stringified for objects. It can be a
                    function or an array of strings.

       space       an optional parameter that specifies the indentation
                    of nested structures. If it is omitted, the text will
                    be packed without extra whitespace. If it is a number,
                    it will specify the number of spaces to indent at each
                    level. If it is a string (such as 't' or ' '),
                    it contains the characters used to indent at each level.

       This method produces a JSON text from a JavaScript value.

检查更新/更好的方式:

  • JSON stringify重新访问
  • 2008年5月17日更新:小型卫生洗涤剂添加到toObject方法。 现在toObject()不会eval()字符串,如果它发现任何恶意代码。为了更安全:不要将includeFunctions标志设置为true。

    JSON概念之父Douglas Crockford为JavaScript编写了第一个字符串。 后来在Trim Path的Steve Yen写了一个很好的改进版本,我用了一段时间。 这是我对史蒂夫版本的改变,我想与你分享。 基本上他们是因为我希望制造弦线器:

    • handle and restore cyclical references  
    • include the JavaScript code for functions/methods (as an option)  
    • exclude object members from Object.prototype if needed.
    
    链接地址: http://www.djcxy.com/p/5431.html

    上一篇: Convert JS object to JSON string

    下一篇: How do I test for an empty JavaScript object?