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

How to map nested JSON to an Object structure with functions?

本文关键字:函数 Object 结构 嵌套 JSON 映射      更新时间:2023-09-26

我想映射一个这样的结构:

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

转换为一个对象,该对象包含两个对象数组(stuff和other stuff)。我想建立这个JSON对象的原型,以便我有我所有的功能可用。我希望能够做这样的事情(树是父对象)。tree.display(),其中显示函数将考虑数组的一种类型,并调用函数显示在包含对象上。

有简单的方法吗?有人能给我举个例子吗?我可以使用$.extend这样的函数吗?

this is not working:

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