zoukankan      html  css  js  c++  java
  • js JSON对象属性

    json对象是是一种用于原生json分析的对象,无法对其进行构造函数调用,用java术语 来说,它相当于能够直接使用类方法的工具类
    JSON对象的属性
    parse(text[,reviver]);
    对参数text这一json字符串分析之后 返回一个javascript对象. reviver将会对每个属性调用回调函数,并将返回值赋为属性值
    对于reviver函数
    reviver(key,val){}
    对javascript返回的对象每一个属性调用函数,注意对对象本身也进行一次调用,没有key值,在最后一次,val是对象本身
    如果 reviver 返回一个有效值,则成员值将替换为转换后的值
    如果 reviver 返回它接收的相同值,则不修改成员值
    如果 reviver 返回 null 或 undefined,则删除成员
    见下面代码

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>json</title>
    </head>
    <body>
    <script>
    //json字符串转换为对象
    var s='{"x":1,"y":2,"a":"ajax"}';
    ////键,值 不可以用单引号包裹 或者属性名不是字符串时   会解析错误
    //var s1="{'x':1,'y':2,a:'ajax'}";     2处错误     解析出错
    var json_s=JSON.parse(s);
    for(var i in json_s){
        console.log(i+":"+json_s[i]);
    }
    var s1=JSON.stringify(json_s);
    console.log(s1);
    /*
    x:1
    y:2
    a:ajax
    {"x":1,"y":2,"a":"ajax"}
    */
    //json字符串数组转换为对象的数组
    var arr=JSON.parse("[1,3,5]");
    var arr1=JSON.parse('["a","c","b"]');
    //键,值 不可以用单引号包裹 否者解析错误
    console.log(arr); //[1, 3, 5]
    console.log(arr1);//["a", "c", "b"]
    console.log(Array.isArray(arr));  //true
    
    //将字符串型的json转换为字符串值
    var f=JSON.parse('"for"');
    console.log(f);//for
    console.log(typeof f);//string
    
    var s='{"x":1,"y":2,"a":3,"p":"php"}';
    function reviver(key,val){
        if(key){
            if(!isNaN(val)) {
                return val+1;
            }else{return val.toLocaleUpperCase()}
        }else{ //注意此处 是对对象本身的调用 key为空,val是对象本身,一定要返回对象本身
             return val;
        }
    }
    var sobj2=JSON.parse(s,reviver);
    console.log(sobj2); //Object {x: 2, y: 3, a: 4, p: "PHP"}
    </script>
    </body>
    </html>

    stringify(value[,replacer[,space]])
    将参数value转换为json字符串,replacer会对每个属性调用回调函数,并将返回值赋为属性值,space是输出时的一个缩进字符串

    <script>
    var students = new Array() ; 
    students[0] = "jim"; 
    students[1] = "tom"; 
    students[2] = "lily"; 
    var json = JSON.stringify(students,switchUpper); 
    function switchUpper(key, value) { 
        return value.toString().toUpperCase(); 
    } 
    console.log(json);//"JIM,TOM,LILY"
    </script>
  • 相关阅读:
    iot 表索引dump《2》
    heap表和iot表排序规则不同
    Cannot complete the install because one or more required items could not be found.
    iot表输出按主键列排序,heap表不是
    iot 表主键存放所有数据,且按数据插入顺序排序
    iot表和heap表排序规则不同
    org.eclipse.graphiti.ui.editor.DiagramEditorInput.
    Oracle 排序规则
    perl 异步超时 打印错误
    14.6.3 Grouping DML Operations with Transactions 组DML操作
  • 原文地址:https://www.cnblogs.com/HKUI/p/4662939.html
Copyright © 2011-2022 走看看