繁体   English   中英

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

[英]How to map nested JSON to an Object structure with functions?

我想映射这样的结构:

{ 
    "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();
});

如果您只想显示某些特定字段,则可以尝试此操作,它将给出公司名称:

<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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM