我爱编程

Json

2018-06-21  本文已影响0人  叫我颜先生

简介

语法

JSON 数据的书写格式是:名称/值对。
如:"name" : "ysj"

   //数字
   { "age":30 }

   //JSON 对象在大括号({})中书写
   { "name":"菜鸟教程" , "url":"www.runoob.com" }
   
   //JSON 数组在中括号中书写
   {
      "sites": [
         { "name":"菜鸟教程" , "url":"www.runoob.com" }, 
         { "name":"google" , "url":"www.google.com" }, 
         { "name":"微博" , "url":"www.weibo.com" }
      ]
   }

   //JSON 布尔值可以是 true 或者 false
   { "flag":true }

   //JSON 可以设置 null 值
   { "runoob":null }

访问

    var myObj, x;
    myObj = { "name":"runoob", "alexa":10000, "site":null };
    x = myObj.name;
    //x = myObj["name"];
    var myObj = { "name":"runoob", "alexa":10000, "site":null };
    for (x in myObj) {
        document.getElementById("demo").innerHTML += x + "<br>";
        //document.getElementById("demo").innerHTML += myObj[x] + "<br>";
    }
    myObj = {
        "name":"runoob",
        "alexa":10000,
        "sites": {
            "site1":"www.runoob.com",
            "site2":"m.runoob.com",
            "site3":"c.runoob.com"
        }
    }
    
    //访问
    x = myObj.sites.site1;
    //x = myObj.sites["site1"];
    
    //修改
    myObj.sites.site1 = "www.google.com";
    //myObj.sites["site1"] = "www.google.com";
    
    //删除
    delete myObj.sites.site1;
    //delete myObj.sites["site1"]
    ```
    
    ###数组
    ```
    myObj = {
        "name":"网站",
        "num":3,
        "sites": [
            { "name":"Google", "info":[ "Android", "Google 搜索", "Google 翻译" ] },
            { "name":"Runoob", "info":[ "菜鸟教程", "菜鸟工具", "菜鸟微信" ] },
            { "name":"Taobao", "info":[ "淘宝", "网购" ] }
        ]
    }
    
    //我们可以使用 for-in 来循环访问每个数组
    for (i in myObj.sites) {
        x += "<h1>" + myObj.sites[i].name + "</h1>";
        for (j in myObj.sites[i].info) {
            x += myObj.sites[i].info[j] + "<br>";
        }
    }
    
    //修改
    myObj.sites[1] = "Github";
    
    //删除
    delete myObj.sites[1];
上一篇下一篇

猜你喜欢

热点阅读