用戶端結合javascript調用JSON的例子

來源:互聯網
上載者:User

前面我已經介紹過what is json,下面我通過執行個體來學習在用戶端結合javascript調用JSON的例子.

首先在JSON官方網站提供的一個開源的JSON解析器和字串轉換器:json.js.

根據json.js解釋文檔可以知道:

        array.toJSONString(whitelist)
        boolean.toJSONString()
        date.toJSONString()
        number.toJSONString()
        object.toJSONString(whitelist)
        string.toJSONString()

   上面6個函數可以產出json文本,這不必包括任何周期性參數,非法值會被排除.date的預設轉換是一個ISO字串.你能夠添加toJSONString()函數到任何date對象來獲得不同的呈現.object和array函數包含whitelist參數選項,whitelist是一個字串數組,如果它被提供的話,那麼在whitelist中沒有找到在Objects的keys會被排除.

   string.parseJSON(filter)這個函數解釋json文本來產生對象和數組,它能夠拋出語法錯誤的異常.選項filter參數具有過濾和轉換結果的功能,它能夠接受每一個鍵和值,它能夠返回被使用的值代替原來的值.如果它返回接收的東西,那麼結構會被修改,如果返回undefined(未定義)的話,則成員會被刪除.

  例子:

  //解釋文本,如果鍵包含字串為'date',那麼轉換該值為日期.

            myData = text.parseJSON(function (key, value) {
                return key.indexOf('date') >= 0 ? new Date(value) : value;
            });

   下面是一個將數群組轉換為對應json串的例子:

//事先包含json.js
function toJSONExample(){
 var jNBtn=document.getElementById("jN");
 jNBtn.onclick=function(){
   var continents=new Array();
   continents.push("Europe");//添加元素到數組
      continents.push("Asia");
      continents.push("Australia");
      continents.push("Antarctica");
      continents.push("North America");
      continents.push("South America");
      continents.push("Africa");
   alert("continents數組的JSON呈現是: " +
 continents.toJSONString());
 }
 
 
}

結果:

["Europe","Asia","Australia","Antarctica","North America","South America","Africa"]  下面是一個將原來產生的json串轉換成數組,在這裡需要一個eval函數來解釋json串,eval函數用來接收一個校正javascript代碼的輸入字串,以下的代碼經常需要將json文本轉換為原來的面貌.               var value = eval( "(" + jsonText + ")" );  例子: function toPaseJSONExample(){
  var jNBtn=document.getElementById("jN");
 jNBtn.onclick=function(){
  var ArrayAsJSONText='["Europe","Asia","Australia","Antarctica","North America","South America","Africa"]';
  var continents=eval(ArrayAsJSONText);//校正ArrayAsJSONText數組
    var continents = ArrayAsJSONText.parseJSON();
  document.getElementById("jsonRespose").innerHTML=continents;
  }
 } 結果:  Europe,Asia,Australia,Antarctica,North America,South America,Africa 總結:在這裡,我只是簡單的介紹了JSON在用戶端的應用,toJSONString()以及parseJSON()的使用方法.至於伺服器端(ASP,ASP.NET)如何解釋JSON和使用JSON傳送資料以及運用AJAX和JSON來傳輸資料的應用,我會在以後的日子裡再作介紹.
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.