zoukankan      html  css  js  c++  java
  • JSON学习

    声名json数组:
    var a = [{
        "id": "1",
        "name": "zhangsan",
        "age": "10"
    }, {
        "id": "2",
        "name": "lisi",
        "age": "20"
    }, {
        "id": "3",
        "name": "wangwu",
        "age": "30"
    }];
    json转string: JSON.stringify(a)
    string转json:eval(JSON.stringify(a))
    添加json对象:
    var obj = {"id":"4","name":"zhaoliu","age":"40"};
    a.push(obj);
    删除json对象:delete a[0];//删除数组a当中的第一个对象,但数组长度不会减1;
    添加json元素:
    修改json元素值:
    a[0]["id"] = "2”;//或a[0].id = “2”;
    alert(a[0]["id"]);//2
    删除json元素:
    delete a[0]["id"];//删除数组a当中第一个对象的id元素,key,value同时删除
    alert(a[0]["id"]);//undefined
    格式化json工具:http://tool.oschina.net/codeformat/json
    测试环境说明:使用jsBin测试工具进行测试,http://jsbin.com/?js,output
    var a = [{
        "id": "1",
        "name": "zhangsan",
        "age": "10"
    }, {
        "id": "2",
        "name": "lisi",
        "age": "20"
    }, {
        "id": "3",
        "name": "wangwu",
        "age": "30"
    }];
    
    //json数组转string
    alert(JSON.stringify(a));
    
    //string 转json数组
    alert(eval(JSON.stringify(a)));
    
    ////新增一个对象,数组长度+1
    // var obj = {"id":"4","name":"zhaoliu","age":"40"};
    // a.push(obj);
    // alert(a.length);
    ////删除固定的对象,数组长度不变
    // delete a[4];
    // alert(a.length +"********"+ a[4]);
    
    ////删除对象元素
    // delete a[0]["id"];//或delete a[0].id;
    // alert(a[0]["id"]);
    
    ////添加对象元素
    // a[0].school = "清华";
    // alert(a[0].school);
    JSON字符串与JSON数组之间的相互转换
    var str1 = '{ "name": "cxh", "sex": "man" }';
    var jsonArr = JSON.parse(str1);//转换为json数组
    var jsonstr = JSON.stringify(jsonArr);//转换为json字符串
    
    console.log(jsonArr);
    console.log(jsonstr);
    
    -------------------------
    [object Object] {
      name: "cxh",
      sex: "man"
    }
    "{"name":"cxh","sex":"man"}"
    
    -------------------------
    
  • 相关阅读:
    符号表实现(Symbol Table Implementations)
    揭开枚举类的面纱(Unlocking the Enumeration/enum Mystery)
    玩转指针(Playing with Pointers)
    什么是空间复杂度(What is actually Space Complexity ?)
    论困于记忆之物(随笔感言)
    【未有之有】洛依文明相关
    告别
    【未有之有】洛森修炼体系整理
    【未有之有】洛森十三圣人
    复苏
  • 原文地址:https://www.cnblogs.com/penggy/p/7475850.html
Copyright © 2011-2022 走看看