JSON

来自Blueidea
跳转至: 导航搜索

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,并以文字为基础,易于人阅读,由Douglas Crockford[1]创建。

JSON被Ajax使用得最为频繁,在Ajax中通常被作为XML的替代方案。

JSON的数据格式如下:

{
     siteName: "蓝色理想",
     domin: {
         bbs: "bbs.blueidea.com",
         ucenter: "home.blueidea.com",
         wiki: "wiki.blueidea.com"
     },
     forum: [
         {name: "Adobe Photoshop 专栏", url: "http://bbs.blueidea.com/forum-7-1.html" },
         {name: "Fireworks 专栏", url: "http://bbs.blueidea.com/forum-3-1.html" }
     ],
     Owners: "蓝色",
     Say: function(text){
          alert(text);
     }
}

演示

假设服务器返回了一段JSON,这时候可用JavaScript中eval()[2]函数来创造一个对象。

下面的代码中,假设变量responseText接受服务器返回的JSON字符串:

<script type="text/javascript">

.......

//responseText已经从服务器接收了一段JSON数据

var responseText='{siteName: "蓝色理想",domin: {bbs: "bbs.blueidea.com",ucenter: "home.blueidea.com",wiki: "wiki.blueidea.com"},forum: [{name: "Adobe Photoshop 专栏", url: "http://bbs.blueidea.com/forum-7-1.html" },{name: "Fireworks 专栏", url: "http://bbs.blueidea.com/forum-3-1.html" }],Owners: "蓝色",Say: function(text){alert(text)}}';

//使用eval将JSON数据转换为一个JavaScript对象,该对象用siteObj来保存

eval("var siteObj="+responseText);

//利用对象中的属性

alert("论坛地址是:"+siteObj.domin.bbs);
alert("示例中共有:"+siteObj.forum.length+"个板块");
alert("第二个板块的名字是:"+siteObj.forum[1].name);

//利用对象中的方法

siteObj.Say("欢迎大家来到蓝色理想!!");

</script>


欲了解更多,请前往:维基百科上关于JSON的更多信息>>

备注

  1. Douglas Crockford是 JavaScript 开发社区最知名的权威,是JSON、JSLint、JSMin 和ADSafe 之父,《JavaScript:The Good Parts》一书的作者
  2. 使用eval可能带来安全隐患,请参考JSON and Browser Security