Hierarchical JSON with tree structure
Tag : java , By : user143038
Date : March 29 2020, 07:55 AM
Any of those help I have to make a tree like JSON structure with Java where I have a parent node with multiple children in it and so on. This is my code I have partially done this one but not completely successful to do it ..here is the output I need , Do this: package stackoverflow.questions;
import com.google.gson.*;
import java.util.ArrayList;
import java.util.List;
public class ParentChildApp {
public static class Entry {
private String name;
public Entry(String name) {
this.name = name;
}
private List<Entry> children;
public void add(Entry node){
if (children == null)
children = new ArrayList<Entry>();
children.add(node);
}
}
public static void main(String[] args) {
Entry workNode = new Entry("Work");
workNode.add(new Entry("Effort"));
workNode.add(new Entry("Trust"));
Entry salaryNode = new Entry("Salary");
Entry cultureNode = new Entry("Culture");
cultureNode.add(salaryNode);
cultureNode.add(workNode);
Gson g = new Gson();
System.out.println(g.toJson(cultureNode));
}
}
|
Generate hierarchical JSON tree structure from Django model
Date : March 29 2020, 07:55 AM
Does that help You can do the following: Transform a list of Classifications to a nested dict. Transform nested dict to the required format class Classification:
def __init__(self, kingdom, phylum, klass, species):
self.kingdom = kingdom
self.phylum = phylum
self.klass = klass
self.species = species
from collections import defaultdict
# in order to work with your actual implementation add more levels of nesting
# as lambda: defaultdict(lambda: defaultdict(lambda: defaultdict(list)))
nested_dict = defaultdict(
lambda: defaultdict(
lambda: defaultdict(list)
)
)
for c in all_classifications:
nested_dict[c.kingdom][c.phylum][c.klass].append(c.species)
{
'Kingdom1': {
'Phylum1': {
'Class1': ["Species1", "Species2"],
'Class2': ["Species3", "Species4"],
},
'Phylum2': { ... }
},
'Kingdom2': { 'Phylum3': { ... }, 'Phylum4': {... } }
}
def nested_to_tree(key, source):
result = {'name': key, 'children':[]}
for key, value in source.items():
if isinstance(value, list):
result['children'] = value
else:
child = nested_to_tree(key, value)
result['children'].append(child)
return result
tree = nested_to_tree('root', nested_dict')
|
How to transform flat JavaScript objects array into nested hierarchical JSON structure?
Date : March 29 2020, 07:55 AM
I hope this helps you . Ok, I figured out the following solution, which seems to be working fine. var familiesArr = [ [ { "name": "child1" }, { "name": "parent1" }, { "name": "grandparent1" } ], [ { "name": "child2" }, { "name": "parent2" }, { "name": "grandparent2" } ] ];
var hierarchicalFamilies = createHierarchicalFamilies(familiesArr);
function createHierarchicalFamilies(familiesArr) {
var familyHierarchy = new Array();
for (var i=0; i<familiesArr.length; i++) {
var family = familiesArr[i];
familyHierarchy.push(addFamilyMember(family.slice()));
}
return familyHierarchy;
}
function addFamilyMember(family) {
if (family.length <= 0) {
return null;
}
var familyMemberNode = family[0];
var familyMember = new Object();
familyMember.name = familyMemberNode.name;
familyMember.parent = addFamilyMember(family.slice(1));
return familyMember;
}
|
Convert tree structure to hierarchical array
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further I'd use recursion here to "walk" down the tree. Note that your input tree sometimes uses "children" and sometimes uses "nodes" to denote its array of children; I have changed it to "children" throughout. var wholeTree = [{
"_id": 1,
"title": "node1",
"children": [{
"_id": 11,
"title": "node1.1",
"children": [{
"_id": 111,
"title": "node1.1.1",
"children": [{
"_id": 1111,
"title": "node1.1.1.1",
"children": []
}]
}]
}, {
"_id": 12,
"title": "node1.2",
"children": []
}]
}, {
"_id": 2,
"title": "node2",
"children": [{
"id": 21,
"title": "node2.1",
"children": []
}, {
"_id": 22,
"title": "node2.2",
"children": []
}]
}, {
"_id": 3,
"title": "node3",
"children": [{
"id": 31,
"title": "node3.1",
"children": []
}]
}, {
"_id": 4,
"title": "node4",
"children": [{
"_id": 41,
"title": "node4.1",
"children": []
}]
}];
var flattened = flattenTreeToNodes( wholeTree, null, "" );
$("#output").text( JSON.stringify(flattened) );
function flattenTreeToNodes( tree, parentId, basePath ) {
console.log( parentId, basePath );
function createFlattenedNode( treeNode ) {
var path = parentId?basePath + "," + parentId:"";
return {
"_id": treeNode._id,
title: treeNode.title,
parentId: parentId,
path: path
}
}
var nodes = [];
for(var i=0; i<tree.length; i++) {
var treeNode = tree[i];
var flattenedNode = createFlattenedNode(treeNode);
nodes.push ( flattenedNode );
var flattenedChildren = flattenTreeToNodes( treeNode.children, treeNode._id, flattenedNode.path );
nodes = nodes.concat( flattenedChildren );
}
return nodes;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id='output'>
</pre>
|
Create a JSON object (hierarchical) from a tree structure -Updated code
Date : March 29 2020, 07:55 AM
I wish this helpful for you I am trying to create a JSON object that updates dynamically as a node tree is created. The node tree will accept an input and append it to the tree. And simultaneouly A the json object is updated with the the values: json object shoudl look something like this: , I have resolved this issue! function createTreeRecurse(rootP, parent, level){
var childrenn = parent.children;
// console.log("==>",childrenn);
++level;
for(var i=0; i <childrenn.length; i++){
var child = childrenn[i];
//console.log('==>',child);
var elem = document.createElement('div');
elem.innerHTML = '     '.repeat(level)+'[+]'+ childrenn[i].value;
// console.log("==>",elem.innerHTML);
// console.log("==>",elem.id);
// elem.children = [];
rootP.appendChild(elem);
var inp = document.createElement('input');
inp.classList.add("created");
elem.appendChild(inp);
inp.addEventListener('keypress', function(e){
if(e.keyCode == 13){
var newElem = document.createElement('div');
console.log()
// newElem.innerHTML = inp.value;
newElem.name = inp.value;
newElem.value = inp.value;
newElem.innerHTML = '    '.repeat(level) + '[+]' + inp.value;
newElem.className = 'collapse';
var newObj = createObjProps(newElem);
parent.children.push(newObj);
console.log(newObj);
// inp.value = '';
rootP.appendChild(newElem);
}
})
createTreeRecurse(elem,child,level);
}
}
|