JSON在javaScript中的幾個經典使用

來源:互聯網
上載者:User

來源 http://blog.163.com/xiexiaoming05@126/blog/static/6753898520093275828469/

 JSON (JavaScript Object Notation)一種簡單的資料格式,比xml更輕巧。 JSON 是 JavaScript 原生格式,這意味著在 JavaScript 中處理 JSON 資料不需要任何特殊的 API 或工具包。

JSON的規則很簡單: 對象是一個無序的“‘名稱/值’對”集合。一個對象以“{”(左括弧)開始,“}”(右括弧)結束。每個“名稱”後跟一個“:”(冒號);“‘名稱/值’ 對”之間使用“,”(逗號)分隔。

下面通過一些例子對JSON作一些簡單的介紹:

一、可以通過Javascript中的eval函數把符合一定格式的字串轉化成JSON對象

<script language="javascript">

    function ShowJsonString()

     {

        response = (

            "[{ name: 'Joe', age: '30', gender: 'M'},{ name: 'Chandler', age: '32', gender: 'M'},{ name: 'Rose', age: '31', gender: 'M'}]"   //字串形式

        );

        var response1 = "({ name: 'Vicson', age: '30', gender: 'M'})";   //字串形式,這裡的小括弧不能少

        json = eval(response);

        json1 = eval(response1); 

        alert(json[0].name + "," + json[1].age + "," +  json[2].gender);

        alert(json1.name);

    }

    ShowJsonString();

</script>

二、直接定義JSON對象

<script language="javascript">

    function ShowJsonObject()

    {

        var user =

        {    

            username:"andy",   

            "age":20,   

            "info": { "tel": "25003614", "cellphone": "882"},   

            "address":   

                [   

                    {city:"shenzhen","postcode":"0755"},   

                    {"city":"guangzhou","postcode":"020"}   

                ]             //address是一個數組

        }                     //對象形式

        alert(user.username);

        alert(user.age);   

        alert(user.info.cellphone);   

        alert(user.address[0].city);   

        alert(user.address[0].postcode);

    }

    ShowJsonObject();

</script>

三、對JSON對象的屬性進行賦值

<script language="javascript">

    function SetJsonObject()

    {

         var user=

         {

             "username":"andy"

         }

         user.username = "Tom";

         alert(user.username);

    }

    SetJsonObject();

</script>

四、通過json.js中的parseJSON方法把字串轉化成JSON對象,

    json.js檔案包可以在http://www.json.org/json.js中下載

<script language="javascript" src="json.js"></script>

<script language="javascript">

    function parseJsonEval()

    {

        var str = '{"name":"Violet", "occupation":"character"}';

        var obj = str.parseJSON();

        alert(obj.toJSONString());

        alert(obj.name);

    }

    parseJsonEval();

</script>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.