jQuery源码分析12: jQuery.parseJSON和jQuery.parseXML

jQuery源码分析12: jQuery.parseJSON和jQuery.parseXML

// JSON RegExp
var rvalidchars = /^[\],:{}\s]*$/,
rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,

parseJSON: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
}

// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );

// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( 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 );
},

// 解析XML文件可直接采用window.DOMParser来解析XML数据或者使用IE特有的ActiveXObject来解析XML
parseXML: function( data ) {
var xml, tmp;
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},

实例分析:
var str = '{"name":"hwsl","age":23}';
JSON.parseJSON(str);

http://json.org/json2.js 中提供了另外一个方法stringify提供和parseJSON相反的功能.

var json = '{"name":"hwsl"}';
var jsonObj = eval(json);
alert(jsonObj.name);
浏览器会报 "SyntaxError: Unexpected token :",因为eval会尝试将你的json解释为一个label,这与
<script type="text/javascript">
{ "name" : "hwsl" }
</script>
会报错的原理是一样的.

解决方法:

var json = '{"name":"hwsl"}';
var jsonObj = eval('(' + json + ')');
alert(jsonObj.name); //< "hwsl"

或者采用
eval('var jsonObj = ' + json);
alert(jsonObj.name); //< "hwsl"

你可能感兴趣的:(jquery)