I wrote an html file with javascript code, which reads a json file in flat structure and coverts into tree structure (considering parents of nodes).
The output is stored in
var tree = [];
I fill the tree array by pushing root node ("parent":"null"
) to tree and pushing other nodes to their respective parent nodes.
Finally I put the following alert statement:
alert(JSON.stringify(tree, null, ' '));
I run the HTML file from a WAMP server. The alert displays the message with the content as expected. But, instead of alert, I want to write the data into a file. How do I do this?
I wrote the following code in the html file. abc.js defines a variable named data which stores json data in flat form. I need to replace alert by writing to file.
<html>
<head>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="abc.js"></script>
<script type="text/javascript">
// create a name: node map
var dataMap = data.reduce(function(map, node) {
map[node.id] = node;
return map;
}, {});
// create the tree array
var tree = [];
data.forEach(function(node) {
// add to parent
var parent = dataMap[node.parent];
if (parent) {
// create child array if it doesn't exist
(parent.children || (parent.children = []))
// add node to child array
.push(node);
} else {
// parent is null or missing
tree.push(node);
}
});
alert(JSON.stringify(tree, null, ' '));
</script>
</head>
<body></body>
</html>