I have the following backbone function to read a JSON schema and draw the tree structure (as in the screenshot below). I want to make sure if checking against the type as object/array is alright or if there is a better way to do it.
traverseJSONSchema: function (root, rootName, level, rank, resultPane) {
var height = this.nodeHeight,
width = this.containerWidth,
margin = width / 6,
x = 0,
overhead = rank * margin,
y = level * height;
var tempParent = resultPane.append("g").attr("class", "nested-group");
if (root.type === "object") {
if (rootName !== "") {
var nodeText = rootName + ":" + root.type;
var node = new DataMapper.Models.Node({parent: tempParent, text: nodeText, x: x, y: y, type: this.get('type'), category: "object", height: height, width: width});
node.drawContainerNode(overhead); //leave overhead space and draw text
rank++;
level++;
}
var nestedParent = tempParent.append("g").attr("class", "nested-group");
var keys = root.properties; //select PROPERTIES
for (var i = 0; i < Object.keys(keys).length; i++) { //traverse through each PROPERTY of the object
var keyName = Object.keys(keys)[i];
var key = keys[keyName];
level = this.traverseJSONSchema(key, keyName, level, rank, tempParent);
}
} else if (root.type === "array") {
var keys = root.items; //select ITEMS
if (rootName !== "") {
var nodeText = rootName + ":" + root.type + "[" + keys.type + "]";
var node = new DataMapper.Models.Node({parent: tempParent, text: nodeText, x: x, y: y, type: this.get('type'), category: "array", height: height, width: width});
node.drawContainerNode(overhead);
rank++;
level++;
}
level = this.traverseJSONSchema(keys, "", level, rank, tempParent); //recurse through the items of array
} else if (["string", "integer", "number", "boolean"].indexOf(root.type) > -1) { //when the type is a primitive
tempParent.classed("nested-group", false);
if (rootName !== "") {
var nodeText = rootName + ":" + root.type;
var node = new DataMapper.Models.Node({parent: tempParent, text: nodeText, x: x, y: y, type: this.get('type'), category: root.type, height: height, width: width});
node.drawContainerNode(overhead);
rank++;
level++;
}
}
return level;
}