1:JSON.parse() 将一个json格式的字符串解析成js对象
var s = '{ "employees": [ { "firstName":"John" , "lastName":"Doe" }, { "firstName":"Anna" , "lastName":"Smith" }, { "firstName":"Peter" , "lastName":"Jones" } ] }'
JSON.parse(s)
Object {employees: Array[3]}
2:JSON.stringify()将一个json对象解析成字符串
JSON.stringify(JSON.parse(s))
"{ "employees": [ { "firstName":"John" , "lastName":"Doe" }, { "firstName":"Anna" , "lastName":"Smith" }, { "firstName":"Peter" , "lastName":"Jones" } ] }"
3:jQuery.parseJSON() : 将格式完好的JSON字符串转为与之对应的JavaScript对象 (jquery 方法)
jQuery.parseJSON(s)
结果和JSON.parse(s)一样
4.JSON.parse()和jQuery.parseJSON()的区别:
JSON.parse()是js方法,jQuery.parseJSON()是jquery方法有的浏览器不支持JSON.parse()方法,使用jQuery.parseJSON()方法时,在浏览器支持时会返回执行JSON.parse()方法的结果,否则会返回类似执行eval()方法的结果,以上结论参考jquery 1.9.1 得出:
parseJSON: function( data ) { // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } if ( data === null ) { return data; } if ( typeof data === "string" ) { // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); if ( data ) { // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } } } jQuery.error( "Invalid JSON: " + data ); },