Convert JS object to JSON string
If I defined an object in JS with:
var j={"name":"binchen"};
How can I convert the object to JSON? The output string should be:
'{"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.
Check out updated/better way:
Update May 17, 2008: Small sanitizer added to the toObject-method. Now toObject() will not eval() the string if it finds any malicious code in it.For even more security: Don't set the includeFunctions flag to true.
Douglas Crockford, father of the JSON concept, wrote one of the first stringifiers for JavaScript. Later Steve Yen at Trim Path wrote a nice improved version which I have used for some time. It's my changes to Steve's version that I'd like to share with you. Basically they stemmed from my wish to make the stringifier:
• 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/5432.html
上一篇: 如何在Git的分支上获取更改
下一篇: 将JS对象转换为JSON字符串