从JSON对象解析循环引用 [英] Resolve circular references from JSON object

查看:302
本文介绍了从JSON对象解析循环引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有来自json.net的序列化JSON,那么:

If I have a serialized JSON from json.net like so:

User:{id:1,{Foo{id:1,prop:1}},
FooList{$ref: "1",Foo{id:2,prop:13}}

我想让淘汰输出超过FooList,但我不知道如何继续进行,因为$ ref的东西可以抛出东西。

I want to have knockout output a foreach over FooList but I am not sure how to proceed because the $ref things could throw things.

我认为解决方案是以某种方式强制所有Foos通过不使用来呈现在FooList中:

I'm thinking the solution would be to somehow force all the Foos to be rendered in the FooList by not using:

PreserveReferencesHandling = PreserveReferencesHandling.Objects

但这似乎很浪费..

推荐答案

您从服务器收到的json对象包含循环引用。在使用对象之前,您必须首先从对象中删除所有 $ ref 属性,意味着代替 $ ref:1你必须把这个链接指向的对象。

The json object which you are receiving from the server contains Circular References. Before using the object you should have to first remove all the $ref properties from the object, means in place of $ref : "1" you have to put the object which this link points.

在您的情况下,它可能指向ID为1的用户对象

为此你应该查看 github上的Douglas Crockfords插件。有一个cycle.js可以完成这项工作对于你。

For this you should check out Douglas Crockfords Plugin on github.There is a cycle.js which can do the job for you.

或者您可以使用以下代码(未经测试):

or you can use the following code (not tested) :

function resolveReferences(json) {
    if (typeof json === 'string')
        json = JSON.parse(json);

    var byid = {}, // all objects by id
        refs = []; // references to objects that could not be resolved
    json = (function recurse(obj, prop, parent) {
        if (typeof obj !== 'object' || !obj) // a primitive value
            return obj;
        if ("$ref" in obj) { // a reference
            var ref = obj.$ref;
            if (ref in byid)
                return byid[ref];
            // else we have to make it lazy:
            refs.push([parent, prop, ref]);
            return;
        } else if ("$id" in obj) {
            var id = obj.$id;
            delete obj.$id;
            if ("$values" in obj) // an array
                obj = obj.$values.map(recurse);
            else // a plain object
                for (var prop in obj)
                    obj[prop] = recurse(obj[prop], prop, obj)
            byid[id] = obj;
        }
        return obj;
    })(json); // run it!

    for (var i=0; i<refs.length; i++) { // resolve previously unknown references
        var ref = refs[i];
        ref[0][ref[1]] = byid[refs[2]];
        // Notice that this throws if you put in a reference at top-level
    }
    return json;
}  

如果有帮助请告诉我!

这篇关于从JSON对象解析循环引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆