6

How do I convert delimited strings into a hierarchical JSON in python. I saw a solution for a similar question in jQuery. I have been trying to find a python solution for the same.

Convert delimited string into hierarchical JSON with JQuery

The goal is to generate a hierarchical json of categories from a bunch of URLs which might look like below
sport/tennis/grandslams
sport/chess
sport/chess/players/men
sport/tennis
sport/cricket/stadiums
sport/tennis/players

Community
  • 1
  • 1

2 Answers2

9

You could achieve this with dictionnaries :

initial = ["Fred-Jim","Fred","Fred-Jim-Bob", "Fred-Jim-Jack", "John", "John-Jim"]

result = {}

for item in initial:
    hierarchy = item.split('-')
    local_result = result
    for node in hierarchy:
        local_result = local_result.setdefault(node, {})

print result

Will give you :

{
    'John': {
        'Jim': {}
    }, 
    'Fred': {
        'Jim': {
            'Bob': {},
            'Jack': {}
        }
    }
}
Cédric Julien
  • 69,378
  • 13
  • 112
  • 121
0

Are you looking for json.dumps() from the json module?

edit: oh, ok, I get you now. Maybe something like:

#paths is a list of strings containing the paths you are scraping from your site.
hierarchy = {}
for path in paths:
    cursor = hierarchy
    for part in path.split('/'):
        if part not in cursor:
            cursor[part] = {}
        cursor = cursor[part]
Silas Ray
  • 24,298
  • 5
  • 44
  • 60
  • i am trying to create hierarchically formatted data from the above list of urls, which i can then feed to json.dumps so that i can get a hierarchical json. This example in jQuery perfectly illustrates what I want to achieve http://stackoverflow.com/a/6232943/435089 – Kannappan Sirchabesan Apr 19 '12 at 14:19