如何将嵌套的JSON映射到具有函数的Object结构?

时间:2014-08-08 08:54:01

标签: javascript json

我想映射这样的结构:

{ 
    "stuff": {
        "onetype": [
            {"id":1,"name":"John Doe"},
            {"id":2,"name":"Don Joeh"}
        ],
        "othertype": {"id":2,"company":"ACME"}
    }, 
    "otherstuff": {
        "thing": "some value"
     }
}

到包含2个对象数组的对象(东西和其他东西)。我想为这个JSON对象构建一个原型,以便我可以使用所有的函数。我希望能够做这样的事情(树是父对象)。 tree.display()其中display函数将数组视为一种类型,并调用函数显示在包含的对象上。

有一种简单的方法吗?有人能指出我如何做到这一点的例子吗? 我可以使用像$.extend这样的函数吗?

这不起作用:

$(document).ready(function(){
    JSONString = '\
        {"stuff": \
            {"onetype": \
                [{"id":1,"name":"John Doe"},\
                {"id":2,"name":"Don Joeh"}],\
            "othertype": \
                {"id":2,"company":"ACME"}\
            }, \
        "otherstuff": {"thing": "some value" }\
        }';

    function Tree () {
        this.stuff = new StuffObject();
        this.otherstuff;
        this.showValue = function () {
            $("body").append(this.otherstuff.thing);
        }
    }

    function StuffObject () {
        this.onetype = new Array();
        this.othertype = new OthertypeObject();
    }

    function OthertypeObject () {
        this.id = 0;
        this.company = "unspecified";
        this.showCompany = function(){
            console.log(this.company);
        }
    }

    var firstTree = $.extend(true, new Tree, JSON.parse(JSONString));
    console.log(firstTree);
    firstTree.showValue();
    firstTree.stuff.othertype.showCompany();
});

1 个答案:

答案 0 :(得分:0)

如果您只想显示某个字段,可以尝试此操作,它将显示公司名称:

<script>
    alert("see this");
    JSONString = '\
        {"stuff": \
            {"onetype": \
                [{"id":1,"name":"John Doe"},\
                {"id":2,"name":"Don Joeh"}],\
            "othertype": \
                {"id":2,"company":"ACME"}\
            }, \
        "otherstuff": {"thing": "some value" }\
        }';

    function Tree () {
        this.stuff = new StuffObject();
        this.otherstuff;
        this.showValue = function () {
            $("body").append(this.otherstuff.thing);
        }
    }

    function StuffObject () {
        this.onetype = new Array();
        this.othertype = new OthertypeObject();
    }

    function OthertypeObject () {
        this.id = 0;
        this.company = "unspecified";
        this.showCompany = function(){
            console.log(this.company);
        }
    }

    var firstTree = $.extend(true, new Tree, JSON.parse(JSONString));
   // var x=json_encode(firstTree);
    console.log(firstTree);
    var x = JSON.stringify(firstTree.stuff.othertype.company);
    alert(x);

</script>