6

i'm new to python and i have to build a tree in python after taking in input from a text file
i have the below data in a text file. I have to build a tree in python with the below data using Json

            {
                "component": "A",
                "status": 0,
                "children": [
                    {
                        "component": "AA",
                        "status": 0,
                        "children": [
                            {
                                "component": "AAA",
                                "status": 0,
                                "children": []
                            },
                            {
                                "component": "AAB",
                                "status": 0,
                                "children": []
                            }
                        ]
                    },
                    {
                        "component": "AB",
                        "status": 0,
                        "children": [
                            {
                                "component": "ABA",
                                "status": 0,
                                "children": []
                            },
                            {
                                "component": "ABB",
                                "status": 0,
                                "children": []
                            }
                        ]
                    }
            }

i wrote the below code but it has syntax errors which Im unable to correct if any one can find them

            class node:
                #Construction of Node with component,status and children
                def _init_(self,component=None,status=None,children=None):
                    self.component = component
                    self.status = status
                    if children is None:
                        self.children = [] 
                    else:
                        self.children = children

            #Building Json object from text file            
            class start:
                import json

                f=open("json_file.txt")
                data=json.load(f)
                buildnode(data)


            #Construction of tree through recursion            
            class implementation:
                def buildnode(self,ob):
                    node1= node()
                    node1.component=ob.component
                    node1.status=ob.status
                    node1.children=[]
                    print 'component',component,'','status',status
                    for children in ob:
                        node1.children.add(buildnode(children[i])) 

                    return node1
2
  • The error I'm seeing is a decoding error related to the JSON (it looks like you are missing a closing square bracket on the second to last line) Commented Mar 4, 2013 at 7:26
  • 1
    And the use of a class without invoking an instance of it to call it's buildnode method Commented Mar 4, 2013 at 7:29

2 Answers 2

6
import json

class Node(object):
    def __init__(self, component=None, status=None, level=0):
        self.component = component
        self.status    = status
        self.level     = level
        self.children  = []

    def __repr__(self):        
        return '\n{indent}Node({component},{status},{children})'.format(
                                         indent = self.level*'\t', 
                                         component = self.component,
                                         status = self.status,
                                         children = repr(self.children))
    def add_child(self, child):
        self.children.append(child)    

def tree_builder(obj, level=0):
    node = Node(component=obj['component'], status=obj['status'], level=level)
    for child in obj.get('children',[]):
        node.add_child(tree_builder(child, level=level+1))
    return node

def load_json(filename):
    with open(filename) as f:
        return json.load(f)

obj = load_json('test.json')
tree = tree_builder(obj)
print tree

Output:

Node(A,0,[
    Node(AA,0,[
        Node(AAA,0,[]), 
        Node(AAB,0,[])]), 
    Node(AB,0,[
        Node(ABA,0,[]), 
        Node(ABB,0,[])])])
Sign up to request clarification or add additional context in comments.

2 Comments

+1 for getting the depth code in there and for cleaner class design
My mentor is really pleased seeing this .... i told him i wrote this on my own :P thanks
2

Ok I was able to fix the bugs in your code and now it looks like this:

class node:
    #Construction of Node with component,status and children
    def _init_(self,component=None,status=None,children=None):
        self.component = component
        self.status = status
        if children is None:
            self.children = [] 
        else:
            self.children = children

#Construction of tree through recursion            
class implementation:
    def buildnode(self,ob):
        node1= node()
        node1.component=ob['component']
        node1.status=ob['status']
        node1.children=[]
        print 'component',node1.component,'','status',node1.status
        for children in ob['children']:
            node1.children.append(self.buildnode(children)) 

        return node1

#Building Json object from text file            
class start:
    import json

    f=open("json_file.txt")
    data=json.load(f)
    builder = implementation()
    builder.buildnode(data)

This produces the following output:

component A  status 0
component AA  status 0
component AAA  status 0
component AAB  status 0
component AB  status 0
component ABA  status 0
component ABB  status 0

Here is some explanation for what was needed:

First you are calling your buildnode() before you define it, and it is a class function so you need an instance of the class before you call it. Next when you are calling for values inside a dictionary you need to access them by dictionary['key']. The only other big thing was the way to append to an array is to call .append() and not .add().

4 Comments

Thanks a lot Jason . Can't believe it actually worked, u solved all the issues which even my mentor couldn't catch ... thanks :D
Was your mentor voting on this answer :P Glad I could help :) I'm enjoying learning Python as well
Although you have fixed the syntax errors, this is almost a perfect example of the many things you shouldn't do: two classes, that shouldn't be classes, violating python naming conventions, not closing a file after opening it, etc...
@root, all valid points and you have my up vote. This is something I really love about StackOverflow, a good enough answer is often superseded with an even better one :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.