Parsing JSON (accessing $Ref) Angular

2019-09-13 20:05发布

I have a problem on parsing of my JSON data. On my object 2, I would have the "t_quartier" while the value is just a reference that points to the object 1. How can I get this value if I'm on my item 2?

enter image description here

thank you a lot

1条回答
Evening l夕情丶
2楼-- · 2019-09-13 21:01

You could use this:

angular.module('app').service('commonService', commonService);

function commonService() {

    //DFS for fixing JSON references
    var elements = {}

    this.fixReferences = function (json) {
        var tree = json;

        for (var x in tree) {
            if ((typeof (tree[x]) === 'object') && (tree[x] !== null)) {
                var result = dfsVisit(tree[x]);
                tree[x] = result;
            }
        }

        return tree;
    }

    function dfsVisit(tree) {
        for (var x in tree) {
            if ((typeof (tree[x]) === 'object') && (tree[x] !== null)) {
                var result = dfsVisit(tree[x]);
                tree[x] = result;
            }
        }
        if (tree["$ref"] !== undefined) {
            var ref = tree.$ref;
            if (elements[ref] !== undefined) {
                tree = elements[ref];
            }

        } else if (tree["$id"] !== undefined) {
            var element = tree;
            elements[element.$id] = element;
        }

        return tree;
    }
}

You could define that function wherever you want but a service would be a clean way.

For using it:

angular.module('app').factory('yourService', yourService);

/*@ngInject*/
function yourService($http, commonService) {
    var service = {
        get: get
    };

    return service;

    function get() { 
        return $http.get('Your url').then(function (response) {
            var fixedData = commonService.fixReferences(response.data);
            return fixedData;
        });
    }    
}
查看更多
登录 后发表回答