If you just want to convert between these structures, this is pretty simple. See working fiddle: http://jsfiddle.net/nrabinowitz/vuk94/
function convert(input, rootName) {
// top level
if (Array.isArray(input)) {
return {
"canonical": rootName,
"children": input.map(convert)
};
}
// node
else {
['left', 'right'].forEach(function(side) {
if (input[side]) {
input.children = input.children || [];
input.children.push(convert(input[side]));
delete input[side];
}
});
return input;
}
}
This uses a couple of ECMAScript 1.5 features (Array.isArray
, forEach
, and map
), but if you're using d3 you're probably targeting browsers that support this anyway.