Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ES5-JSON格式 #10

Open
hubvue opened this issue Dec 19, 2018 · 0 comments
Open

ES5-JSON格式 #10

hubvue opened this issue Dec 19, 2018 · 0 comments

Comments

@hubvue
Copy link
Owner

hubvue commented Dec 19, 2018

ES5提供了一个全局的JSON对象,用来序列化(JSON.strigify)和反序列化(JSON.parse)对象为JSON对象。

对于老式的浏览器,可以使用json2.js,可以让旧的浏览器实现同样的功能。

JSON.parse

接受文本并转换成一个ECMAScript的值 可选的reviver参数是带有key和value两个参数的函数,用于是对文本的所转的值做一次过滤。

//不带第二个参数
var result = JSON.parse('{"a" : 1, "b" :2}');
console.log(result);      {a : 1,b : 2} 
//带第二个参数
 var result = JSON.parse('{"a":"1","b" : 2}',function(key,value){
    if(typeof value == "string"){
        return parseInt(value);
    }else {
        return value;
    }
});
console.log(result);

JSON.stringify

将传入的对象进行序列化,第二个参数提供一个可选的函数,参数为key和value对传入对象进行过滤。

当value值为undefined的时候,该对应属性不会被序列化。

第三个为space参数,表示被序列化,每个属性的格式化前的空格数。

//一个参数
var obj = {
    name : "wang",
    age : 21,
}
var result = JSON.stringify(obj);
console.log(result);
//二个参数
var obj = {
    name : "wang",
    age : 21,
}
var result = JSON.stringify(obj,function(key,value){
    if(key == "age"&& value >20){
        return value =18;
    } else {
        return value;
    }
})
console.log(result);
//三个参数
var  obj = {
    name : "zhou",
    age : 21,
}
var result = JSON.stringify(obj,function(key,value){
    if(key == "age" && value > 20){
        return value = 18;
    }else {
         return value;
    }
},4);
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant