JSON
是JavaScript的原生對象畏吓,用來處理JSON格式數(shù)據(jù)兆解,提供兩個靜態(tài)方法
JSON.stringify()
和JSON.parse()
- JSON格式形如
["one", "two", "three"]
{ "one": 1, "two": 2, "three": 3 }
{"names": ["張三", "李四"] }
[ { "name": "張三"}, {"name": "李四"} ]
- stringify()
如果一個對象有toJSON
方法 使用stringify方法就會直接調(diào)用這個方法
var user = {
firstName: '三',
lastName: '張',
get fullName(){
return this.lastName + this.firstName;
},
toJSON: function () {
return {
name: this.lastName + this.firstName
};
}
};
JSON.stringify(user)
// "{"name":"張三"}"
-
parse
相當(dāng)于JSON.stringify 同樣可以接受一個處理函數(shù)
function f(key, value) {
if (key === 'a') {
return value + 10;
}
return value;
}
JSON.parse('{"a": 1, "b": 2}', f)
// {a: 11, b: 2}
判斷一個字符串是不是JSON格式的字符串
if (typeof str == 'string') {
try {
var obj=JSON.parse(str);
if(typeof obj == 'object' && obj ){
return true;
}else{
return false;
}
} catch(e) {
console.log('error:'+str+'!!!'+e);
return false;
}
}
console.log('It is not a string!')
}