JS object to JSON string?
如何在javascript函数中将javascript对象转换为JSON字符串?我需要将JSON字符串传递到JSP页面。
有两个采样方法的图书馆(AS Crockford提出red"匿名):
一个对象的JSON字符串。
1 2 3 4 | var obj = JSON.parse('{"property":"value" }'); alert (obj.property); // value |
一个对象的JSON字符串。
1 2 3 4 | var str = JSON.stringify({"property":"value" }) alert (str); //{"property":"value" } |
有内置的方法,所以这样做在大多数的主要框架。
quoth Crockford(http:/ / / js.html www.json.org):
To convert a JSON text into an object,
you can use the eval() function.
eval() invokes the JavaScript
compiler. Since JSON is a proper
subset of JavaScript, the compiler
will correctly parse the text and
produce an object structure. The text
must be wrapped in parens to avoid
tripping on an ambiguity in
JavaScript's syntax.var myObject = eval('(' + myJSONtext +
')');The eval function is very fast.
However, it can compile and execute
any JavaScript program, so there can
be security issues. The use of eval is
indicated when the source is trusted
and competent. It is much safer to use
a JSON parser. ...To defend against this, a JSON parser
should be used. A JSON parser will
recognize only JSON text, rejecting
all scripts. In browsers that provide
native JSON support, JSON parsers are
also much faster than eval. It is
expected that native JSON support will
be included in the next ECMAScript
standard.var myObject = JSON.parse(myJSONtext,
reviver);
然后他在剩余的JSON的原型开发的文章。
用于Firefox的Gecko版本(3和3.5支持JSON natively(http://developer.mozilla.org /恩/ JSON),这可能是有用的,如果你的项目是A公司基于应用到最近的壁虎。
下面是指定出兴趣的一部分,文本发电机(需要解析器)是在github.com douglascrockford http://////js json的BLOB和主/从一个json2.js
A JSON stringifier goes in the opposite direction, converting JavaScript data structures into JSON text. JSON does not support cyclic data structures, so be careful to not give cyclical structures to the JSON stringifier.
var myJSONText = JSON.stringify(myObject, replacer);
循环数据结构和对象是不usefully serialized显然是有只大警告。
它是值得一提的匿名的链接(http://www.json.org / js.html)想点你在正确的方向,因为页面包括信息关于如何stringify所以JavaScript和JSON数据结构A文本:
A JSON stringifier goes in the opposite direction, converting JavaScript data structures into JSON text.
特别是,寻找链接页面底点,在开源的stringifier JSON解析器和JSON。