var oObject = JSON.parse (sJSON);
同时,它也提供了一种将 Javascript 对象转换为 JSON 字符串(数据传输时使用的)的工具(在Javascript 中没有内建这种功能支持)。你要做的只是将对象传入到 JSON.Stringify() 方法。请看下面的例子:
var oCar = new Object();
oCar.doors = 4;
oCar.color = "blue";
oCar.year = 1995;
oCar.drivers = new Array("Penny", "Dan" , "Kris");
document.write(JSON.stringify(oCar));
这段代码将输出如下所示的JSON 字符串:
{"doors" : 4, "color" : "blue", "year" :1995, "drivers" : ["Penny", "Dan" , "Kris"]}
2. JSON 与 XML
正如上面所说,JSON 与 XML 相比的一大优点就是它更加简单。
请看 XML 数据表示实例:
使用XML表示:
<comments>
<comment>
<id>1</id>
<author>someone1</author>
<url>http://someone1.x2design.net</url>
<content>hello</content>
</comment>
<comment>
<id>2</id>
<author>someone2</author>
<url>http://someone2.x2design.net</url>
<content>someone1</content>
</comment>
<comment>
<id>3</id>
<author>someone3</author>
<url>http://someone3.x2design.net</url>
<content>hello</content>
</comment>
</comments>
使用JSON表示:
{comments:[
{
id:1,
author:"someone1",
url:"http://someone1.x2design.net",
content:"hello"
},
{
id:2,
author:"someone2",
url:"http://someone2.x2design.net",
content:"hello"
},
{
id:3,
author:"someone3",
url:"http://someone3.x2design.net",
content:"hello"
}
]};
很容易发现,许多冗余的信息不见了。由于不需要有与开始标签(opening tag)匹配的结束标签(closing tag),因此传送相同的信息所需的字节数大大降低了。创始人 Corockford 将其称之为“XML 的减肥方案”)。
JSON 格式的数据与 XML 相比,缺点是对于外行人可读性更差。当然,有一种观点是,数据交换格式不是用肉眼观察的。如果是通过工具对来回传送的数据进行创建和解析,那么的确没有理由要求数据必须使人们易于阅读。问题的实质在于:存在可用的 JSON 工具。
3. 服务器端 JSON 工具
java :java JSON 工具,由Douglas Crock ford 开发,可在 www.crockford.com/JSON/java/
中下载,它可以在 JSP 中使用。
4. JSON 优势与缺点
JSON不仅减少了解析XML解析带来的性能问题和兼容性问题,而且对于javascript来说非常容易使用,可以方便的通过遍历数组以及访问对象属性来获取数据,其可读性也不错,基本具备了结构化数据的性质。不得不说是一个很好的办法,而且事实上google maps就没有采用XML传递数据,而是采用了JSON方案。









