ANY JSON tree (DRAFT)
This example displays any JSON object as an interactive tree diagram, allowing users to explore nested data structures and their values. The tree renders in SVG, with nodes labeled by key names and showing their type (object, array, string, number, etc.) alongside the value. The code uses D3 v5’s `tree` layout and `hierarchy` to structure the data, with `linkHorizontal` for the connecting paths and a zoom behavior for panning. Node labels are generated by a custom `hierarchify` function that recursively converts the JSON into a hierarchical format, and clicking branches toggles their children to collapse or expand the tree.
AI-generated descriptionAim: Display ANY JSON as a selectable tree.
The idea is to be able to use d3 as a JSON-explorer / picker.
Version 1.0 using the code from World Countries Tree from Curran
Other Possible GUIs
- Collapsible Tree from MikeBostock on [Observable]
- D3 collapsing tree with boxes from swayvil on [bl.ocks.org]
- d3 JSON data to tree / cluster (switchable) layout from Sundar Singh on [bl.ocks.org]
https://bl.ocks.org/swayvil/b86f8d4941bdfcbfff8f69619cd2f460
Probably the d3.tree is what we want to use ...
1. Restructure the data into hierarchical JSON format
The JSON format expected by a d3 tree
See function hierarchify in
https://observablehq.com/@d3/collapsible-tree
Alternative ideas:
- See Stack exchange D3 JSON data conversion
var input = [
{ "dep": "d1", "name": "name1", "size": "size1" },
{ "dep": "d1", "name": "name2", "size": "size2" },
{ "dep": "d2", "name": "name1", "size": "size3" },
{ "dep": "d2", "name": "name1", "size": "size4" }
];
var output = {
"name": "root",
"children": d3.groups(input, d => d.dep).map(([k, vs]) => ({ "name": k, "children": vs }))
};
2. Present the hierarchical JSON as a tree
- See d3 | JSON data to tree layout
- or many others
3. Make the hierarchie interactive
…
4. Clicking a node should return the JSONPath to that node.
…