您的位置:首页 > Web前端 > JavaScript

前台解决Json数据中出现"$ref"的问题

2016-12-10 11:51 393 查看
当我们使用fastjson的时候,这个组件"很聪明",他会自动判断对象或者对象中是否有互相调用的死循环,从而用一些特殊的符号代替,这里就给出在js中解决问题的办法,小金子也是别的地方拿来的,也是通过混淆的,但是这不影响使用.

只要在你使用之前调用一下这句话

FastJson.format(data);  //data是后台返回的json数据,里面有$ref字样的字符串,这是前面所说的fastjson处理的,但是通过这句话都能进行替换,把我们需要的数据还原回来

//页面解决json中$ref问题

    var FastJson = {

        isArray : function(a) {

            return "object" == typeof a

                    && "[object array]" == Object.prototype.toString.call(a)

                            .toLowerCase();

        },

        isObject : function(a) {

            return "object" == typeof a

                    && "[object object]" == Object.prototype.toString.call(a)

                            .toLowerCase();

        },

        format : function(a) {

            if (null == a)

                return null;

            "string" == typeof a && (a = eval("(" + a + ")"));

            return this._format(a, a, null, null, null);

        },

        _randomId : function() {

            return "randomId_" + parseInt(1E9 * Math.random());

        },

        _getJsonValue : function(a, c) {

            var d = this._randomId(), b;

            b = "" + ("function " + d + "(root){") + ("return root." + c + ";");

            b += "}";

            b += "";

            var e = document.createElement("script");

            e.id = d;

            e.text = b;

            document.body.appendChild(e);

            d = window[d](a);

            e.parentNode.removeChild(e);

            return d;

        },

        _format : function(a, c, d, b, e) {

            d || (d = "");

            if (this.isObject(c)) {

                if (c.$ref) {

                    var g = c.$ref;

                    0 == g.indexOf("$.")

                            && (b[e] = this._getJsonValue(a, g.substring(2)));

                    return

                }

                for ( var f in c)

                    b = d, "" != b && (b += "."), g = c[f], b += f, this

                            ._format(a, g, b, c, f);

            } else if (this.isArray(c))

                for (f in c)

                    b = d, g = c[f], b = b + "[" + f + "]", this._format(a, g,

                            b, c, f);

            return a;

        }

    };
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  json fastjson
相关文章推荐