json2.js

作者:ca88

这段日子,境遇了json格式在JS和Jquey的蒙受中,需求互相调换,在网络查了一下,大多为缺胳膊少腿,恐怕作者是菜鸟吧,终于测验成功后,依旧给初学者们贰个实例吧  

    var cx = /[­u0600-u0604u070fu17b4u17b5u200c-u200fu2028-u202fu2060-u206fufeffufff0-uffff]/g,
        escapable = /[\"x00-x1fx7f-x9fu00adu0600-u0604u070fu17b4u17b5u200c-u200fu2028-u202fu2060-u206fufeffufff0-uffff]/g,
        gap,
        indent,
        meta = {    // table of character substitutions
            'b': '\b',
            't': '\t',
            'n': '\n',
            'f': '\f',
            'r': '\r',
            '"' : '\"',
            '\': '\\'
        },
        rep;

你或者感兴趣的稿子:

  • 依照jQuery.Hz2Py.js插件完结的方块字转拼音特效
  • 由此jQuery塑造帮助汉字,拼音,斯洛伐克语连忙牢固查询的一流select插件
  • 听说jquery的使ListNav包容普通话首字拼音排序的达成代码
  • jquery中完毕时间戳与日期相互调换
  • Jquery中扩张参数与Json转变代码
  • jquery 将日前光阴转移成yyyymmdd格式的兑现形式
  • jquery实现将赚取的颜色值转变为十六进制格局的法子
  • jquery怎么样把参数列严厉调换成数组完毕思路
  • jquery对象和DOM对象的私下相互变换
  • jquery对象和DOM对象的交互转变详解
  • jQuery完结QQ空间汉字转拼音效率示例

            throw new SyntaxError('JSON.parse');
        };
    }
}());

复制代码 代码如下:
/*
   
    Public Domain.
    NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
    See
    This code should be minified before deployment.
    See
    USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
    NOT CONTROL.
    This file creates a global JSON object containing two methods: stringify
    and parse.
        JSON.stringify(value, replacer, space)
            value       any JavaScript value, usually an object or array.
            replacer    an optional parameter that determines how object
                        values are stringified for objects. It can be a
                        function or an array of strings.
            space       an optional parameter that specifies the indentation
                        of nested structures. If it is omitted, the text will
                        be packed without extra whitespace. If it is a number,
                        it will specify the number of spaces to indent at each
                        level. If it is a string (such as 't' or ' '),
                        it contains the characters used to indent at each level.
            This method produces a JSON text from a JavaScript value.
            When an object value is found, if the object contains a toJSON
            method, its toJSON method will be called and the result will be
            stringified. A toJSON method does not serialize: it returns the
            value represented by the name/value pair that should be serialized,
            or undefined if nothing should be serialized. The toJSON method
            will be passed the key associated with the value, and this will be
            bound to the value
            For example, this would serialize Dates as ISO strings.
                Date.prototype.toJSON = function (key) {
                    function f(n) {
                        // Format integers to have at least two digits.
                        return n < 10 ? '0' n : n;
                    }
                    return this.getUTCFullYear()   '-'
                         f(this.getUTCMonth() 1) '-'
                         f(this.getUTCDate())      'T'
                         f(this.getUTCHours())     ':'
                         f(this.getUTCMinutes())   ':'
                         f(this.getUTCSeconds())   'Z';
                };
            You can provide an optional replacer method. It will be passed the
            key and value of each member, with this bound to the containing
            object. The value that is returned from your method will be
            serialized. If your method returns undefined, then the member will
            be excluded from the serialization.
            If the replacer parameter is an array of strings, then it will be
            used to select the members to be serialized. It filters the results
            such that only members with keys listed in the replacer array are
            stringified.
            Values that do not have JSON representations, such as undefined or
            functions, will not be serialized. Such values in objects will be
            dropped; in arrays they will be replaced with null. You can use
            a replacer function to replace those with JSON values.
            JSON.stringify(undefined) returns undefined.
            The optional space parameter produces a stringification of the
            value that is filled with line breaks and indentation to make it
            easier to read.
            If the space parameter is a non-empty string, then that string will
            be used for indentation. If the space parameter is a number, then
            the indentation will be that many spaces.
            Example:
            text = JSON.stringify(['e', {pluribus: 'unum'}]);
            // text is '["e",{"pluribus":"unum"}]'
            text = JSON.stringify(['e', {pluribus: 'unum'}], null, 't');
            // text is '[nt"e",nt{ntt"pluribus": "unum"nt}n]'
            text = JSON.stringify([new Date()], function (key, value) {
                return this[key] instanceof Date ?
                    'Date(' this[key] ')' : value;
            });
            // text is '["Date(---current time---)"]'
        JSON.parse(text, reviver)
            This method parses a JSON text to produce an object or array.
            It can throw a SyntaxError exception.
            The optional reviver parameter is a function that can filter and
            transform the results. It receives each of the keys and values,
            and its return value is used instead of the original value.
            If it returns what it received, then the structure is not modified.
            If it returns undefined then the member is deleted.
            Example:
            // Parse the text. Values that look like ISO date strings will
            // be converted to Date objects.
            myData = JSON.parse(text, function (key, value) {
                var a;
                if (typeof value === 'string') {
                    a =
/^(d{4})-(d{2})-(d{2})T(d{2}):(d{2}):(d{2}(?:.d*)?)Z$/.exec(value);
                    if (a) {
                        return new Date(Date.UTC( a[1], a[2] - 1, a[3], a[4],
                            a[5], a[6]));
                    }
                }
                return value;
            });
            myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
                var d;
                if (typeof value === 'string' &&
                        value.slice(0, 5) === 'Date(' &&
                        value.slice(-1) === ')') {
                    d = new Date(value.slice(5, -1));
                    if (d) {
                        return d;
                    }
                }
                return value;
            });
    This is a reference implementation. You are free to copy, modify, or
    redistribute.
*/
/*jslint evil: true, strict: false, regexp: false */
/*members "", "b", "t", "n", "f", "r", """, JSON, "", apply,
    call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
    getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
    lastIndex, length, parse, prototype, push, replace, slice, stringify,
    test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
if (!this.JSON2)
{
    this.JSON2 = {};
}
(function () {
    "use strict";
    function f(n) {
        // Format integers to have at least two digits.
        return n < 10 ? '0' n : n;
    }
    if (typeof Date.prototype.toJSON !== 'function') {
        Date.prototype.toJSON = function (key) {
            return isFinite(this.valueOf()) ?
                   this.getUTCFullYear()   '-'
                 f(this.getUTCMonth() 1) '-'
                 f(this.getUTCDate())      'T'
                 f(this.getUTCHours())     ':'
                 f(this.getUTCMinutes())   ':'
                 f(this.getUTCSeconds())   'Z' : null;
        };
        String.prototype.toJSON =
        Number.prototype.toJSON =
        Boolean.prototype.toJSON = function (key) {
            return this.valueOf();
        };
    }
    var cx = /[u0000u00adu0600-u0604u070fu17b4u17b5u200c-u200fu2028-u202fu2060-u206fufeffufff0-uffff]/g,
        escapable = /["x00-x1fx7f-x9fu00adu0600-u0604u070fu17b4u17b5u200c-u200fu2028-u202fu2060-u206fufeffufff0-uffff]/g,
        gap,
        indent,
        meta = {    // table of character substitutions
            'b': 'b',
            't': 't',
            'n': 'n',
            'f': 'f',
            'r': 'r',
            '"' : '"',
            '': ''
        },
        rep;
    function quote(string) {
        escapable.lastIndex = 0;
        return escapable.test(string) ?
            '"' string.replace(escapable, function (a) {
                var c = meta[a];
                return typeof c === 'string' ? c :
                    'u' ('0000' a.charCodeAt(0).toString(16)).slice(-4);
            }) '"' :
            '"' string '"';
    }
    function str(key, holder) {
        var i,          // The loop counter.
            k,          // The member key.
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];
        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }
        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }
        switch (typeof value) {
        case 'string':
            return quote(value);
        case 'number':
            return isFinite(value) ? String(value) : 'null';
        case 'boolean':
        case 'null':
            return String(value);
        case 'object':
            if (!value) {
                return 'null';
            }
            gap = indent;
            partial = [];
            if (Object.prototype.toString.apply(value) === '[object Array]') {
                length = value.length;
                for (i = 0; i < length; i = 1) {
                    partial[i] = str(i, value) || 'null';
                }
                v = partial.length === 0 ? '[]' :
                    gap ? '[n' gap
                            partial.join(',n' gap) 'n'
                                mind ']' :
                          '[' partial.join(',') ']';
                gap = mind;
                return v;
            }
            if (rep && typeof rep === 'object') {
                length = rep.length;
                for (i = 0; i < length; i = 1) {
                    k = rep[i];
                    if (typeof k === 'string') {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) (gap ? ': ' : ':') v);
                        }
                    }
                }
            } else {
                for (k in value) {
                    if (Object.hasOwnProperty.call(value, k)) {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) (gap ? ': ' : ':') v);
                        }
                    }
                }
            }
            v = partial.length === 0 ? '{}' :
                gap ? '{n' gap partial.join(',n' gap) 'n'
                        mind '}' : '{' partial.join(',') '}';
            gap = mind;
            return v;
        }
    }
    if (typeof JSON2.stringify !== 'function') {
        JSON2.stringify = function (value, replacer, space) {
            var i;
            gap = '';
            indent = '';
            if (typeof space === 'number') {
                for (i = 0; i < space; i = 1) {
                    indent = ' ';
                }
            } else if (typeof space === 'string') {
                indent = space;
            }
            rep = replacer;
            if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                     typeof replacer.length !== 'number')) {
                throw new Error('JSON2.stringify');
            }
            return str('', {'': value});
        };
    }
    if (typeof JSON2.parse !== 'function') {
        JSON2.parse = function (text, reviver) {
            var j;
            function walk(holder, key) {
                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }
            text = String(text);
            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return 'u'
                        ('0000' a.charCodeAt(0).toString(16)).slice(-4);
                });
            }
            if (/^[],:{}s]*$/
.test(text.replace(/(?:["/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"nr]*"|true|false|null|-?d (?:.d*)?(?:[eE][ -]?d )?/g, ']')
.replace(/(?:^|:|,)(?:s*[) /g, ''))) {
                j = eval('(' text ')');
                return typeof reviver === 'function' ?
                    walk({'': j}, '') : j;
            }
            throw new SyntaxError('JSON2.parse');
        };
    }
}());

        Date.prototype.toJSON = function (key) {

第二、调用页的剧情
小心:调用js文件的门道需求本身调度,那一点即使不会,那就别再持续看了。

            Example:

...

            Values that do not have JSON representations, such as undefined or
            functions, will not be serialized. Such values in objects will be
            dropped; in arrays they will be replaced with null. You can use
            a replacer function to replace those with JSON values.
            JSON.stringify(undefined) returns undefined.

复制代码 代码如下:

            var i;
            gap = '';
            indent = '';

第一,准备新建贰个js文件。以下是JSON2.js的内容,把内容拷到js文件中,以便调用:

            Example:

复制代码 代码如下:

// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.

复制代码 代码如下:

        JSON.parse(text, reviver)
            This method parses a JSON text to produce an object or array.
            It can throw a SyntaxError exception.

  •                         mind '}' : '{' partial.join(',') '}';
                gap = mind;
                return v;
            }
        }
        if (typeof JSON2.stringify !== 'function') {
            JSON2.stringify = function (value, replacer, space) {
                var i;
                gap = '';
                indent = '';
                if (typeof space === 'number') {
                    for (i = 0; i < space; i = 1) {
                        indent = ' ';
                    }
                } else if (typeof space === 'string') {
                    indent = space;
                }
                rep = replacer;
                if (replacer && typeof replacer !== 'function' &&
                        (typeof replacer !== 'object' ||
                         typeof replacer.length !== 'number')) {
                    throw new Error('JSON2.stringify');
                }
                return str('', {'': value});
            };
        }
        if (typeof JSON2.parse !== 'function') {
            JSON2.parse = function (text, reviver) {
                var j;
                function walk(holder, key) {
                    var k, v, value = holder[key];
                    if (value && typeof value === 'object') {
                        for (k in value) {
                            if (Object.hasOwnProperty.call(value, k)) {
                                v = walk(value, k);
                                if (v !== undefined) {
                                    value[k] = v;
                                } else {
                                    delete value[k];
                                }
                            }
                        }
                    }
                    return reviver.call(holder, key, value);
                }
                text = String(text);
                cx.lastIndex = 0;
                if (cx.test(text)) {
                    text = text.replace(cx, function (a) {
                        return '\u'
                            ('0000' a.charCodeAt(0).toString(16)).slice(-4);
                    });
                }
                if (/^[],:{}s]*$/
    .test(text.replace(/\(?:["\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
    .replace(/"[^"\nr]*"|true|false|null|-?d (?:.d*)?(?:[eE][ -]?d )?/g, ']')
    .replace(/(?:^|:|,)(?:s*[) /g, ''))) {
                    j = eval('(' text ')');
                    return typeof reviver === 'function' ?
                        walk({'': j}, '') : j;
                }
                throw new SyntaxError('JSON2.parse');
            };
        }
    }());

            The optional space parameter produces a stringification of the
            value that is filled with line breaks and indentation to make it
            easier to read.

第二、调用页的剧情
瞩目:调用js文件的路径须求自个儿调节,那一点假诺不会,那就别再持续看了。

        escapable.lastIndex = 0;
        return escapable.test(string) ?
            '"' string.replace(escapable, function (a) {
                var c = meta[a];
                return typeof c === 'string' ? c :
                    '\u' ('0000' a.charCodeAt(0).toString(16)).slice(-4);
            }) '"' :
            '"' string '"';
    }

   <script src="../jquery/jquery-1.5.2.min.js" type="text/javascript"></script>
    <script src="../json2.js" type="text/javascript"></script>
        var a = '{ "name": "tom", "sex": "男", "age": "24" }';    // 用于组成json的字符串;
        alert("用于组成json的字符串:【" a "】");
        var b = JSON2.parse(a);   // 把字符串a调换为json格式b
        var c = JSON2.stringify(a); //把json格式b转变为字符串c
        alert("调换后的字符串:【" c "】");

// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

   <script src="../jquery/jquery-1.5.2.min.js" type="text/javascript"></script>
    <script src="../json2.js" type="text/javascript"></script>
        var a = '{ "name": "tom", "sex": "男", "age": "24" }';    // 用于组成json的字符串;
        alert("用于组成json的字符串:【" a "】");
        var b = JSON2.parse(a);   // 把字符串a转换为json格式b
        var c = JSON2.stringify(a); //把json格式b转变为字符串c
        alert("转变后的字符串:【" c "】");

        var c = JSON2.stringify(a); //把json格式b调换为字符串c
        alert("转变后的字符串:【" c "】");

第一,希图新建三个js文件。以下是JSON2.js的剧情,把内容拷到js文件中,以便调用:

            if (rep && typeof rep === 'object') {
                length = rep.length;
                for (i = 0; i < length; i = 1) {
                    if (typeof rep[i] === 'string') {
                        k = rep[i];
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) (gap ? ': ' : ':') v);
                        }
                    }
                }
            } else {

 

/*
   
    Public Domain.
    NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
    See
    This code should be minified before deployment.
    See
    USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
    NOT CONTROL.
    This file creates a global JSON object containing two methods: stringify
    and parse.
        JSON.stringify(value, replacer, space)
            value       any JavaScript value, usually an object or array.
            replacer    an optional parameter that determines how object
                        values are stringified for objects. It can be a
                        function or an array of strings.
            space       an optional parameter that specifies the indentation
                        of nested structures. If it is omitted, the text will
                        be packed without extra whitespace. If it is a number,
                        it will specify the number of spaces to indent at each
                        level. If it is a string (such as 't' or ' '),
                        it contains the characters used to indent at each level.
            This method produces a JSON text from a JavaScript value.
            When an object value is found, if the object contains a toJSON
            method, its toJSON method will be called and the result will be
            stringified. A toJSON method does not serialize: it returns the
            value represented by the name/value pair that should be serialized,
            or undefined if nothing should be serialized. The toJSON method
            will be passed the key associated with the value, and this will be
            bound to the value
            For example, this would serialize Dates as ISO strings.
                Date.prototype.toJSON = function (key) {
                    function f(n) {
                        // Format integers to have at least two digits.
                        return n < 10 ? '0' n : n;
                    }
                    return this.getUTCFullYear()   '-'
                         f(this.getUTCMonth() 1) '-'
                         f(this.getUTCDate())      'T'
                         f(this.getUTCHours())     ':'
                         f(this.getUTCMinutes())   ':'
                         f(this.getUTCSeconds())   'Z';
                };
            You can provide an optional replacer method. It will be passed the
            key and value of each member, with this bound to the containing
            object. The value that is returned from your method will be
            serialized. If your method returns undefined, then the member will
            be excluded from the serialization.
            If the replacer parameter is an array of strings, then it will be
            used to select the members to be serialized. It filters the results
            such that only members with keys listed in the replacer array are
            stringified.
            Values that do not have JSON representations, such as undefined or
            functions, will not be serialized. Such values in objects will be
            dropped; in arrays they will be replaced with null. You can use
            a replacer function to replace those with JSON values.
            JSON.stringify(undefined) returns undefined.
            The optional space parameter produces a stringification of the
            value that is filled with line breaks and indentation to make it
            easier to read.
            If the space parameter is a non-empty string, then that string will
            be used for indentation. If the space parameter is a number, then
            the indentation will be that many spaces.
            Example:
            text = JSON.stringify(['e', {pluribus: 'unum'}]);
            // text is '["e",{"pluribus":"unum"}]'
            text = JSON.stringify(['e', {pluribus: 'unum'}], null, 't');
            // text is '[nt"e",nt{ntt"pluribus": "unum"nt}n]'
            text = JSON.stringify([new Date()], function (key, value) {
                return this[key] instanceof Date ?
                    'Date(' this[key] ')' : value;
            });
            // text is '["Date(---current time---)"]'
        JSON.parse(text, reviver)
            This method parses a JSON text to produce an object or array.
            It can throw a SyntaxError exception.
            The optional reviver parameter is a function that can filter and
            transform the results. It receives each of the keys and values,
            and its return value is used instead of the original value.
            If it returns what it received, then the structure is not modified.
            If it returns undefined then the member is deleted.
            Example:
            // Parse the text. Values that look like ISO date strings will
            // be converted to Date objects.
            myData = JSON.parse(text, function (key, value) {
                var a;
                if (typeof value === 'string') {
                    a =
/^(d{4})-(d{2})-(d{2})T(d{2}):(d{2}):(d{2}(?:.d*)?)Z$/.exec(value);
                    if (a) {
                        return new Date(Date.UTC( a[1], a[2] - 1, a[3], a[4],
                            a[5], a[6]));
                    }
                }
                return value;
            });
            myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
                var d;
                if (typeof value === 'string' &&
                        value.slice(0, 5) === 'Date(' &&
                        value.slice(-1) === ')') {
                    d = new Date(value.slice(5, -1));
                    if (d) {
                        return d;
                    }
                }
                return value;
            });
    This is a reference implementation. You are free to copy, modify, or
    redistribute.
*/
/*jslint evil: true, strict: false, regexp: false */
/*members "", "b", "t", "n", "f", "r", """, JSON, "\", apply,
    call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
    getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
    lastIndex, length, parse, prototype, push, replace, slice, stringify,
    test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
if (!this.JSON2)
{
    this.JSON2 = {};
}
(function () {
    "use strict";
    function f(n) {
        // Format integers to have at least two digits.
        return n < 10 ? '0' n : n;
    }
    if (typeof Date.prototype.toJSON !== 'function') {
        Date.prototype.toJSON = function (key) {
            return isFinite(this.valueOf()) ?
                   this.getUTCFullYear()   '-'
                 f(this.getUTCMonth() 1) '-'
                 f(this.getUTCDate())      'T'
                 f(this.getUTCHours())     ':'
                 f(this.getUTCMinutes())   ':'
                 f(this.getUTCSeconds())   'Z' : null;
        };
        String.prototype.toJSON =
        Number.prototype.toJSON =
        Boolean.prototype.toJSON = function (key) {
            return this.valueOf();
        };
    }
    var cx = /[­u0600-u0604u070fu17b4u17b5u200c-u200fu2028-u202fu2060-u206fufeffufff0-uffff]/g,
        escapable = /[\"x00-x1fx7f-x9fu00adu0600-u0604u070fu17b4u17b5u200c-u200fu2028-u202fu2060-u206fufeffufff0-uffff]/g,
        gap,
        indent,
        meta = {    // table of character substitutions
            'b': '\b',
            't': '\t',
            'n': '\n',
            'f': '\f',
            'r': '\r',
            '"' : '\"',
            '\': '\\'
        },
        rep;
    function quote(string) {
        escapable.lastIndex = 0;
        return escapable.test(string) ?
            '"' string.replace(escapable, function (a) {
                var c = meta[a];
                return typeof c === 'string' ? c :
                    '\u' ('0000' a.charCodeAt(0).toString(16)).slice(-4);
            }) '"' :
            '"' string '"';
    }
    function str(key, holder) {
        var i,          // The loop counter.
            k,          // The member key.
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];
        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }
        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }
        switch (typeof value) {
        case 'string':
            return quote(value);
        case 'number':
            return isFinite(value) ? String(value) : 'null';
        case 'boolean':
        case 'null':
            return String(value);
        case 'object':
            if (!value) {
                return 'null';
            }
            gap = indent;
            partial = [];
            if (Object.prototype.toString.apply(value) === '[object Array]') {
                length = value.length;
                for (i = 0; i < length; i = 1) {
                    partial[i] = str(i, value) || 'null';
                }
                v = partial.length === 0 ? '[]' :
                    gap ? '[n' gap
                            partial.join(',n' gap) 'n'
                                mind ']' :
                          '[' partial.join(',') ']';
                gap = mind;
                return v;
            }
            if (rep && typeof rep === 'object') {
                length = rep.length;
                for (i = 0; i < length; i = 1) {
                    k = rep[i];
                    if (typeof k === 'string') {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) (gap ? ': ' : ':') v);
                        }
                    }
                }
            } else {
                for (k in value) {
                    if (Object.hasOwnProperty.call(value, k)) {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) (gap ? ': ' : ':') v);
                        }
                    }
                }
            }
            v = partial.length === 0 ? '{}' :
                gap ? '{n' gap partial.join(',n' gap) 'n'

                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.prototype.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }

            text = JSON.stringify([new Date()], function (key, value) {
                return this[key] instanceof Date ?
                    'Date(' this[key] ')' : value;
            });
            // text is '["Date(---current time---)"]'

                return typeof reviver === 'function'
                    ? walk({'': j}, '')
                    : j;
            }

   <script src="../jquery/jquery-1.5.2.min.js" type="text/javascript"></script>
    <script src="../json2.js" type="text/javascript"></script>

/*jslint evil: true, regexp: true */

(function () {
    "use strict";

            text = JSON.stringify(['e', {pluribus: 'unum'}], null, 't');
            // text is '[nt"e",nt{ntt"pluribus": "unum"nt}n]'

    function quote(string) {

                Date.prototype.toJSON = function (key) {
                    function f(n) {
                        // Format integers to have at least two digits.
                        return n < 10 ? '0' n : n;
                    }

/*
   
    2010-11-17

            return isFinite(this.valueOf())
                ? this.getUTCFullYear()     '-'
                    f(this.getUTCMonth() 1) '-'
                    f(this.getUTCDate())      'T'
                    f(this.getUTCHours())     ':'
                    f(this.getUTCMinutes())   ':'
                    f(this.getUTCSeconds())   'Z'
                : null;
        };

 

// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.

            myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
                var d;
                if (typeof value === 'string' &&
                        value.slice(0, 5) === 'Date(' &&
                        value.slice(-1) === ')') {
                    d = new Date(value.slice(5, -1));
                    if (d) {
                        return d;
                    }
                }
                return value;
            });

// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.

    NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

            text = String(text);
            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return '\u'
                        ('0000' a.charCodeAt(0).toString(16)).slice(-4);
                });
            }

        var b = JSON2.parse(a);   // 把字符串a转变为json格式b

            The optional reviver parameter is a function that can filter and
            transform the results. It receives each of the keys and values,
            and its return value is used instead of the original value.
            If it returns what it received, then the structure is not modified.
            If it returns undefined then the member is deleted.

// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.

// If the replacer is an array, use it to select the members to be stringified.

 

            if (!value) {
                return 'null';
            }

            // Parse the text. Values that look like ISO date strings will
            // be converted to Date objects.

// If the JSON object does not yet have a stringify method, give it one.

/*members "", "b", "t", "n", "f", "r", """, JSON, "\", apply,
    call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
    getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
    lastIndex, length, parse, prototype, push, replace, slice, stringify,
    test, toJSON, toString, valueOf
*/

    var cx = /[u0000u00adu0600-u0604u070fu17b4u17b5u200c-u200fu2028-u202fu2060-u206fufeffufff0-uffff]/g,
        escapable = /[\"x00-x1fx7f-x9fu00adu0600-u0604u070fu17b4u17b5u200c-u200fu2028-u202fu2060-u206fufeffufff0-uffff]/g,
        gap,
        indent,
        meta = {    // table of character substitutions
            'b': '\b',
            't': '\t',
            'n': '\n',
            'f': '\f',
            'r': '\r',
            '"' : '\"',
            '\': '\\'
        },
        rep;

    This is a reference implementation. You are free to copy, modify, or
    redistribute.
*/

            space       an optional parameter that specifies the indentation
                        of nested structures. If it is omitted, the text will
                        be packed without extra whitespace. If it is a number,
                        it will specify the number of spaces to indent at each
                        level. If it is a string (such as 't' or ' '),
                        it contains the characters used to indent at each level.

    USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
    NOT CONTROL.

// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.

            myData = JSON.parse(text, function (key, value) {
                var a;
                if (typeof value === 'string') {
                    a =
/^(d{4})-(d{2})-(d{2})T(d{2}):(d{2}):(d{2}(?:.d*)?)Z$/.exec(value);
                    if (a) {
                        return new Date(Date.UTC( a[1], a[2] - 1, a[3], a[4],
                            a[5], a[6]));
                    }
                }
                return value;
            });

// If the space parameter is a string, it will be used as the indent string.

近日,境遇了json格式在JS和Jquey的条件中,要求互相转变,在网络查了须臾间,许多为缺胳膊少腿,也许笔者是新手吧,终于测量检验成功后,照旧给初学者们二个实例吧。

        switch (typeof value) {
        case 'string':
            return quote(value);

    function str(key, holder) {
        var i,          // The loop counter.
            k,          // The member key.
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];
        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }
        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }
        switch (typeof value) {
        case 'string':
            return quote(value);
        case 'number':
            return isFinite(value) ? String(value) : 'null';
        case 'boolean':
        case 'null':
            return String(value);
        case 'object':
            if (!value) {
                return 'null';
            }
            gap = indent;
            partial = [];
            if (Object.prototype.toString.apply(value) === '[object Array]') {
                length = value.length;
                for (i = 0; i < length; i = 1) {
                    partial[i] = str(i, value) || 'null';
                }
                v = partial.length === 0 ? '[]' :
                    gap ? '[n' gap
                            partial.join(',n' gap) 'n'
                                mind ']' :
                          '[' partial.join(',') ']';
                gap = mind;
                return v;
            }
            if (rep && typeof rep === 'object') {
                length = rep.length;
                for (i = 0; i < length; i = 1) {
                    k = rep[i];
                    if (typeof k === 'string') {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) (gap ? ': ' : ':') v);
                        }
                    }
                }
            } else {
                for (k in value) {
                    if (Object.hasOwnProperty.call(value, k)) {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) (gap ? ': ' : ':') v);
                        }
                    }
                }
            }
            v = partial.length === 0 ? '{}' :
                gap ? '{n' gap partial.join(',n' gap) 'n'

    if (typeof Date.prototype.toJSON !== 'function') {

 

// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.

            replacer    an optional parameter that determines how object
                        values are stringified for objects. It can be a
                        function or an array of strings.

    This code should be minified before deployment.
    See

本文由ca88发布,转载请注明来源

关键词: ca88网址 JS