parse json nary tree in javascript

To parse a n-ary tree in JSON format in Javascript, you can use a recursive approach.

First, assume you have a JSON string representing the n-ary tree. You can parse the string into a Javascript object using JSON.parse().

index.tsx
const jsonString = '{ "value": 1, "children": [{ "value": 2, "children": [{ "value": 4, "children": [] }, { "value": 5, "children": [] }] }, { "value": 3, "children": [] }] }';
const tree = JSON.parse(jsonString);
214 chars
3 lines

In this example, the n-ary tree has a value property and a children property which is an array of child trees.

Then, you can define a recursive function that takes a tree node as an argument and does some action with it, such as printing its value.

index.tsx
function printTree(node) {
  console.log(node.value);
  node.children.forEach(child => printTree(child));
}
108 chars
5 lines

This function prints the value of the current node and then recurses through its children array, calling itself with each child node as the argument.

To parse the entire tree, you can simply call the function with the root node of the tree.

index.tsx
printTree(tree);
17 chars
2 lines

This will print the values of all nodes in the tree in a depth-first traversal order.

Note that this example assumes that the children property of each node is an array. If the children property is not an array, you will need to modify the function accordingly.

related categories

gistlibby LogSnag