zoukankan      html  css  js  c++  java
  • jquery工具方法parseJSON

    error : 自定义错误

    parseJSON : 字符串转json

    trim : 去除字符串头尾空字符

    parseJSON方法先判断参数是否为字符串,否则返回空对象,再去除字符串头尾空字符,判断是否支持window.JSON.parse,否则使用json2.js中的方法。

    var core_trim = String.prototype.trim,
        // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
        rtrim = /^[suFEFFxA0]+|[suFEFFxA0]+$/g,
        // JSON RegExp
        rvalidchars = /^[],:{}s]*$/,
        rvalidbraces = /(?:^|:|,)(?:s*[)+/g,
        rvalidescape = /\(?:["\/bfnrt]|u[da-fA-F]{4})/g,
        rvalidtokens = /"[^"\
    ]*"|true|false|null|-?(?:dd*.|)d+(?:[eE][-+]?d+|)/g;
    
    
    jQuery.extend({
    
        ......................
    
        error: function( msg ) {
            throw new Error( msg );
        },
    
        parseJSON: function( data ) {
            if ( !data || typeof data !== "string") {
                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 );
        },
    
        // Use native String.trim function wherever possible
        trim: core_trim && !core_trim.call("uFEFFxA0") ?
            function( text ) {
                return text == null ?
                    "" :
                    core_trim.call( text );
            } :
    
            // Otherwise use our own trimming functionality
            function( text ) {
                return text == null ?
                    "" :
                    ( text + "" ).replace( rtrim, "" );
            },
    
        ...............
    
    });
  • 相关阅读:
    Samba配置文件常用参数详解-OK
    SVN Server配置详解 及备份
    secure crt 基本设置***
    ultraedit15.00.0.1046注册码
    makefile中的shell语法 ***
    Spring (一) IOC ( Inversion Of Control )
    软件开发过程中会出来的几个版本
    poj3070
    Python基础 3----文件和网络
    HDU 4720 Naive and Silly Muggles (外切圆心)
  • 原文地址:https://www.cnblogs.com/gongshunkai/p/5902078.html
Copyright © 2011-2022 走看看