当前位置: 首页 > 图文教程 > 网络编程 > Javascript > 看了就知道什么是JSON

Javascript
javascript 关闭IE6、IE7
javascript substr和substring用法比较
javascript 强制弹出窗口代码-跨拦截
javascript 获取多条数据(模拟ajax获取数据)
js 分页代码带切换效果
选择指定数量后checkbox不可选(变灰)javascript代码
javascript 图片上传预览-兼容标准
jquery 截取字符串的实现
jquery tagname 取得方法
scrollTop 用法说明
javascript 倒排序方法
慎用 somefunction.prototype 分析
几个常用的JavaScript字符串处理函数 - split()、join()、substring()和indexOf()
javascript 根据歌名获取播放地址和歌词内容
js在Firefox与IE中对DOM对像的引用的比较
Javascript String对象扩展HTML编码和解码的方法
javascript HTMLEncode HTMLDecode的完整实例(兼容ie和火狐)
Javascript 获取字符串字节数的多种方法
javascript 常用方法总结
cookie丢失问题(认证失效) Authentication (用户验证信息)也会丢失

Javascript 中的 看了就知道什么是JSON


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 459 ::
收藏到网摘: n/a

什么是JSON
JSON(Javascript Object Notation) 是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于Javascript Programming Language, Standard ECMA-262 3rd Edition - December 1999的一个子集。JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, Javascript, Perl, Python等)。这些特性使JSON成为理想的数据交换语言。
JSON概念很简单,就是服务器直接生成Javascript语句,客户端获取后直接用eval方法来获得这个对象,这样就可以省去解析XML的性损失。
使用XML表示:
复制代码 代码如下:

<items>
<item>
<id>1</id>
<author>Jackson</author>
<url>http://www.ruanchen.com</url>
<content>Welcome to Web.cn</content>
</item>
<item>
<id>2</id>
<author>Relkn</author>
<url>http://www.ruanchen.com</url>
<content>Web.cn关注互联网新技术</content>
</item>
<item>
<id>3</id>
<author>Kvogend</author>
<url>http://www.ruanchen.com</url>
<content>ruanchen.com软晨学习网</content>
</item>
</items>

代码:
复制代码 代码如下:

<items>
<item>
<id>1</id>
<author>Jackson</author>
<url>http://www.ruanchen.com</url>
<content>Welcome to Web.cn</content>
</item>
<item>
<id>2</id>
<author>Relkn</author>
<url>http://www.ruanchen.com</url>
<content>Web.cn关注互联网新技术</content>
</item>
<item>
<id>3</id>
<author>Kvogend</author>
<url>http://www.ruanchen.com</url>
<content>ruanchen.com软晨学习网</content>
</item>
</items>

使用JSON:
复制代码 代码如下:

{items:[
{
id:1,
author:\"Jackson\",
url:\"http://www.ruanchen.com\",
content:\"Welcome to Web.cn\"
},
{
id:2,
author:\"Relkn\",
url:\"http://www.ruanchen.com\",
content:\"Web.cn关注互联网新技术\"
},
{
id:3,
author:\"Kvogend\",
url:\"http://www.ruanchen.com\",
content:\"ruanchen.com软晨学习网\"
}
]};

代码:
复制代码 代码如下:

{items:[
{
id:1,
author:\"Jackson\",
url:\"http://www.ruanchen.com\",
content:\"Welcome to Web.cn\"
},
{
id:2,
author:\"Relkn\",
url:\"http://www.ruanchen.com\",
content:\"Web.cn关注互联网新技术\"
},
{
id:3,
author:\"Kvogend\",
url:\"http://www.ruanchen.com\",
content:\"ruanchen.com软晨学习网\"
}
]};

JSON不仅减少了解析XML解析带来的性能问题和兼容性问题,而且对于Javascript来说非常容易使用,可以方便的通过遍历数组以及访问对象属性来获取数据,其可读性也不错,基本具备了结构化数据的性质。不得不说是一个很好的办法,而且事实上google maps就没有采用XML传递数据,而是采用了JSON方案。
JSON的另外一个优势是"跨域性",例如你在www.ruanchen.com的网页里使用
<script type="text/javascript" src="" target="_blank">http://www.yyy.com/some.js">
是完全可行的,这就意味着你可以跨域传递信息。而使用XMLHttpRequest却获取不了跨域的信息,这是Javascript内部的安全性质所限制的。
JSON能完全取代XML吗?当然不能,原因就在于XML的优势:通用性。要使服务器端产生语法合格的Javascript代码并不是很容易做到的,这主要发生在比较庞大的系统,服务器端和客户端有不同的开发人员。它们必须协商对象的格式,这很容易造成错误。