Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert delimited string to hierarchical JSON in python

Tags:

python

json

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  
like image 858
Kannappan Sirchabesan Avatar asked Apr 19 '12 14:04

Kannappan Sirchabesan


1 Answers

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': {}
        }
    }
}
like image 196
Cédric Julien Avatar answered Sep 22 '22 05:09

Cédric Julien