Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6578845
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T15:49:24+00:00 2026-05-25T15:49:24+00:00

I’m sure there’s an elegant way of doing this in Python (or at a

  • 0

I’m sure there’s an elegant way of doing this in Python (or at a push, Javascript), but for the life of me I can’t see it…

I have a CSV file of the form:

ID, Name, Description
A, A-name,
A100, A100-name, A100-desc
A110, A110-name, A110-desc
A111, A111-name, A111-desc
A112, A112-name, A112-desc
A113, A113-name, A113-desc
A120, A120-name, A120-desc
A131, A131-name, A131-desc
A200, A200-name, A200-desc
B, B-name,
B100, B100-name, B100-desc
B130, B130-name, B130-desc
B131, B131-name, B131-desc
B140, B140-name, B140-desc

and I want to generate a hierarchical JSON structure so I can visualise the data in theJIT.

var json = {  
  "id": "aUniqueIdentifier",  
  "name": "usually a nodes name",  
  "data": {  
    "some key": "some value",  
    "some other key": "some other value"  
   },  
  "children": [ *other nodes or empty* ]  
}; 

My plan was to map ID to id, Name to name, Description to data.desc, and organise the hierarchy so that:

  • Root is parent of A and B
  • A is parent of A100 and A200
  • A100 is parent of A110 and A120
  • A110 is parent of A111, A112 and A113
  • B is parent of B100
  • B100 is parent of B130 and B140
  • B130 is parent of B131

There is also a pathological case in the otherwise regular ordering by ID, where A100 is parent of A131 (the expected A130 is not present).

I was hoping to find an elegant Python solution to this, but it’s defeating me at the moment, even ignoring the pathological case…

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T15:49:25+00:00Added an answer on May 25, 2026 at 3:49 pm

    This does it…

    import csv
    import json
    
    class Node(dict):
        def __init__(self, (nid, name, ndescr)):
            dict.__init__(self)
            self['id'] = nid
            self['name'] = name.lstrip() # you have badly formed csv....
            self['description'] = ndescr.lstrip()
            self['children'] = []
    
        def add_node(self, node):
            for child in self['children']:
                if child.is_parent(node):
                    child.add_node(node)
                    break
            else:
                self['children'].append(node)
    
        def is_parent(self, node):
            if len(self['id']) == 4 and self['id'][-1] == '0':
                return node['id'].startswith(self['id'][:-1])
            return node['id'].startswith(self['id'])
    
    class RootNode(Node):
        def __init__(self):
            Node.__init__(self, ('Root', '', ''))
    
        def is_parent(self, node):
            return True
    
    def pretty_print(node, i=0):
        print '%sID=%s NAME=%s %s' % ('\t' * i, node['id'], node['name'], node['description'])
        for child in node['children']:
            pretty_print(child, i + 1)
    
    def main():
        with open('input.csv') as f:
            f.readline() # Skip first line
            root = RootNode()
            for node in map(Node, csv.reader(f)):
                root.add_node(node)
    
        pretty_print(root)
        print json.dumps(root)
    
    if __name__ == '__main__':
        main()
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I have a jquery bug and I've been looking for hours now, I can't
this is what i have right now Drawing an RSS feed into the php,
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
Does anyone know how can I replace this 2 symbol below from the string
I have this code to decode numeric html entities to the UTF8 equivalent character.
I have just tried to save a simple *.rtf file with some websites and
link Im having trouble converting the html entites into html characters, (&# 8217;) i

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.