1,JSON.parse() ps: ( JQ中有一个 $.parseJSON() 作用类似 )
将字符串解析成对象 (注意:单引号写在{}/[]外,每个属性名都必须用双引号,否则会抛出异常)
var str1 = '{ "name":"leo" , "sex":"man" , "job":"coder" }';
console.log(JSON.parse(str1));
{ name: "leo", sex: "man", job: "coder" } //变为json
var str2 = '["ewae","wwww","wwww"]';
console.log(JSON.parse(str2));
["ewae","wwww","wwww"] // 变为数组
2,JSON.stringify() 将对象解析成字符串
var json1 = { name: "leo", sex: "man", job: "coder" };
console.log(JSON.stringify(json1));
'{ name: "leo", sex: "man", job: "coder" }' // 变为字符串
var json2 = [1,2,3,4,5];
console.log(JSON.stringify(json2)); // 变为字符串
3.serialize() 输出序列化表单值
<form action="">
First name: <input type="text" name="FirstName" value="Bill" /><br />
Last name: <input type="text" name="LastName" value="Gates" /><br />
</form>
<button>序列化表单值</button>
$("button").click(function(){
$("div").text($("form").serialize());
});
输出:FirstName=Bill&LastName=Gates
将字符串解析成对象 (注意:单引号写在{}/[]外,每个属性名都必须用双引号,否则会抛出异常)
var str1 = '{ "name":"leo" , "sex":"man" , "job":"coder" }';
console.log(JSON.parse(str1));
{ name: "leo", sex: "man", job: "coder" } //变为json
var str2 = '["ewae","wwww","wwww"]';
console.log(JSON.parse(str2));
["ewae","wwww","wwww"] // 变为数组
2,JSON.stringify() 将对象解析成字符串
var json1 = { name: "leo", sex: "man", job: "coder" };
console.log(JSON.stringify(json1));
'{ name: "leo", sex: "man", job: "coder" }' // 变为字符串
var json2 = [1,2,3,4,5];
console.log(JSON.stringify(json2)); // 变为字符串
3.serialize() 输出序列化表单值
<form action="">
First name: <input type="text" name="FirstName" value="Bill" /><br />
Last name: <input type="text" name="LastName" value="Gates" /><br />
</form>
<button>序列化表单值</button>
$("button").click(function(){
$("div").text($("form").serialize());
});
输出:FirstName=Bill&LastName=Gates