一:字符串转换为对象:使用JSON.parse()方法
var str = '{ "name": "AndrewNeo", "sex": "man" }';
var newstr = JSON.parse(str);
console.log(newstr);
console.log(typeof(newstr));//object
二:JSON对象转换为字符串:使用JSON.stringify()方法
var person = {
"name":"AndrewNeo",
"age":25,
"sex":"man"
}
var newperson = JSON.stringify(person);
console.log(newperson);
console.log(typeof(newperson));//string
备注:在Firefox,chrome,opera,safari,ie9,ie8等高级浏览器直接可以用JSON对象的stringify()和parse()方法。ie8(兼容模式),ie7和ie6没有JSON对象,使用需引入json.js。
不推荐使用eval()方法将字符串转换为JSON对象
本文介绍了如何使用JSON.parse()方法将字符串转换为对象,以及如何使用JSON.stringify()方法将JSON对象转换为字符串。此外还提到了在不同浏览器中的兼容性问题,并推荐了避免使用eval()方法。
1170

被折叠的 条评论
为什么被折叠?



