[英]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.