convert delimited string to hierarchical JSON in python

json, python

Solution

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': {}
        }
    }
}

Problem

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 ```

Original source

Related problems