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  
                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': {}
        }
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With