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

当使用Fastjson解析JSON数据时,遇到$ref表示存在循环引用的情况。本文介绍了如何在前端通过JavaScript的FastJson对象来处理这个问题,通过FastJson.format(data)方法可以将$ref替换为实际值,从而还原JSON数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当我们使用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;
        }
    };

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值