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.)

The goal is to generate a hierarchical JSON of categories from a bunch of URLs which might look like:

sport/tennis/grandslams  
sport/chess  
sport/chess/players/men  
sport/tennis  
sport/cricket/stadiums  
sport/tennis/players  
smci
  • 32,567
  • 20
  • 113
  • 146
Kannappan Sirchabesan
  • 1,353
  • 11
  • 21

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
  • 78,516
  • 15
  • 127
  • 132
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
  • 25,682
  • 5
  • 48
  • 63
  • 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